412. Fizz Buzz
这是一题使用判断条件的题目,还考察了求余数,我使用了map()方法。
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"
]
解1:
class Solution(object):
def change(self, num):
if num % 15 == 0:
return "FizzBuzz"
elif num % 5 == 0:
return "Buzz"
elif num % 3 == 0:
return "Fizz"
else :
return str(num)
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return map(self.change, range(1,n+1))
84.81%
解2
def fizzBuzz(self, n):
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]
使用了列表解析,和字符串相加相乘的想法,更加精炼。