Python版本:python3.6.2
412. Fizz Buzz
Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. Example: n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
交作业啦
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
for i in range(1, n+1):
if not i % 3 and not i % 5:
res.append("FizzBuzz")
elif not i % 3:
res.append("Fizz")
elif not i % 5:
res.append("Buzz")
else:
res.append(str(i))
return res
检验一下:a = Solution()
print(a.fizzBuzz(15))
运行结果:"D:\Program files\python3.6.2\python.exe" "D:/sunfl/sunflower/study/LeetCode/412. Fizz Buzz/412. Fizz Buzz.py"
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
进程已结束,退出代码0
速度:这是迄今为止我最好的成绩了,超过50%啦哈哈哈,感觉有点没出息,没事慢慢来,每天进步一点点o(* ̄▽ ̄*)ブ
再来看看大神代码:
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
def fizzBuzz(self, n):
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n + 1)]
这里胜在想法,通过字符串拼接的方式省去了if else的判断,简洁漂亮!要注意:
or:
print("1" or "2") #返回1
print("fffff" or "2") #返回fffff
这里,or 作或判断,“1”、“2”、"fffff"都被视为真,故返回最左边的那个。