题目

写一个程序,输出从1到n数字的字符串表示。

  1. 如果n是3的倍数,输出”Fizz”;
  2. 如果n是5的倍数,输出”Buzz”;
  3. 如果n同时是3和5的倍数,输出”FizzBuzz”。

image.png

思路

一、暴力法

  1. class Solution:
  2. def fizzBuzz(self, n: int) -> List[str]:
  3. ans = []
  4. for i in range(1, n+1):
  5. if i % 3 == 0:
  6. if i % 5 == 0:
  7. ans.append('FizzBuzz')
  8. else:
  9. ans.append('Fizz')
  10. elif i % 5 == 0:
  11. ans.append('Buzz')
  12. else:
  13. ans.append(str(i))
  14. return ans

填一下官方代码,写得确实优雅。

  1. class Solution:
  2. def fizzBuzz(self, n):
  3. """
  4. :type n: int
  5. :rtype: List[str]
  6. """
  7. # ans list
  8. ans = []
  9. for num in range(1,n+1):
  10. divisible_by_3 = (num % 3 == 0)
  11. divisible_by_5 = (num % 5 == 0)
  12. if divisible_by_3 and divisible_by_5:
  13. # Divides by both 3 and 5, add FizzBuzz
  14. ans.append("FizzBuzz")
  15. elif divisible_by_3:
  16. # Divides by 3, add Fizz
  17. ans.append("Fizz")
  18. elif divisible_by_5:
  19. # Divides by 5, add Buzz
  20. ans.append("Buzz")
  21. else:
  22. # Not divisible by 3 or 5, add the number
  23. ans.append(str(num))
  24. return ans

二、字符串连接

image.png

  1. class Solution:
  2. def fizzBuzz(self, n):
  3. """
  4. :type n: int
  5. :rtype: List[str]
  6. """
  7. # ans list
  8. ans = []
  9. for num in range(1,n+1):
  10. divisible_by_3 = (num % 3 == 0)
  11. divisible_by_5 = (num % 5 == 0)
  12. num_ans_str = ""
  13. if divisible_by_3:
  14. # Divides by 3
  15. num_ans_str += "Fizz"
  16. if divisible_by_5:
  17. # Divides by 5
  18. num_ans_str += "Buzz"
  19. if not num_ans_str:
  20. # Not divisible by 3 or 5
  21. num_ans_str = str(num)
  22. # Append the current answer str to the ans list
  23. ans.append(num_ans_str)
  24. return ans

三、更优雅且具有扩展性的实现:散列表

  1. class Solution:
  2. def fizzBuzz(self, n):
  3. """
  4. :type n: int
  5. :rtype: List[str]
  6. """
  7. # ans list
  8. ans = []
  9. # Dictionary to store all fizzbuzz mappings
  10. fizz_buzz_dict = {3 : "Fizz", 5 : "Buzz"}
  11. for num in range(1,n+1):
  12. num_ans_str = ""
  13. for key in fizz_buzz_dict.keys():
  14. # If the num is divisible by key,
  15. # then add the corresponding string mapping to current num_ans_str
  16. if num % key == 0:
  17. num_ans_str += fizz_buzz_dict[key]
  18. if not num_ans_str:
  19. num_ans_str = str(num)
  20. # Append the current answer str to the ans list
  21. ans.append(num_ans_str)
  22. return ans