1.题目
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’]
2.分析
感觉就是if else 判断。看了一圈答案也没有更好的。遍历一遍而已。
不同之处可能在于如何把代码写的更短吧。
3.代码
def fizzBuzz(self, n):
def f(i):
if i%15==0:
return "FizzBuzz"
elif i%3==0:
return "Fizz"
elif i%5==0:
return "Buzz"
else:
return str(i)
return map(f,xrange(1,n+1))
再附上solution里面一行搞定的代码:
def fizzBuzz(self, n):
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]