python--leetcode412. Fizz Buzz

来源:互联网 发布:淘宝复古女装海报下载 编辑:程序博客网 时间:2024/05/21 09:31

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到这个数的所有数字,如果是3的倍数就输出“Fizz”,如果是5的倍数就输出“Buzz”,如果同时是3和5的倍数就输出“FizzBuzz”。

依题意得代码:

class Solution(object):    def fizzBuzz(self, n):        """        :type n: int        :rtype: List[str]        """        list=[]        for i in range(n):            i=i+1            if i%3==0 and i%5==0:list.append("FizzBuzz")            elif i%3==0 : list.append("Fizz")            elif i%5==0:list.append("Buzz")            else :list.append(str(i))        return lists=Solution()print(s.fizzBuzz(15))
很简单其实。

还有一种一行代码解决的可供参考:

return [str(i) if (i%3!=0 and i%5!=0) else (('Fizz'*(i%3==0)) + ('Buzz'*(i%5==0))) for i in range(1,n+1)]
有兴趣的同学可以研究一下python的正则匹配。

原创粉丝点击