9. Fizz Buzz 问题
题目
给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
- 如果这个数被3整除,打印
fizz
. - 如果这个数被5整除,打印
buzz
. - 如果这个数能同时被
3
和5
整除,打印fizz buzz
.
样例
比如 n = 15
, 返回一个字符串数组:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
挑战
Can you do it with only one if
statement?
题解
def fizzBuzz(self, n): # write your code here lst = [] for i in range(1, n+1): word = str(i) if i % 3 == 0: word = "fizz" if i % 5 == 0: word = "buzz" if i % 15 == 0: word = "fizz buzz" lst.append(word) return lst