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的正则匹配。
阅读全文
1 0
- python--leetcode412. Fizz Buzz
- leetcode412: Fizz Buzz
- Leetcode412. Fizz Buzz
- [LeetCode412] Fizz Buzz
- Leetcode412. Fizz Buzz
- leetcode412. Fizz Buzz
- 20.leetCode412: Fizz Buzz
- Leetcode412. Fizz Buzz爱美之心人皆有之
- 【LeetCode-Python】412. Fizz Buzz
- [leetcode: Python]412.Fizz Buzz
- Fizz Buzz
- Fizz Buzz
- Fizz Buzz
- Fizz Buzz
- Fizz Buzz
- Fizz Buzz
- Fizz Buzz
- Fizz Buzz
- 【NOIP2016】天天爱跑步之树上差分
- 前端面试题(HTML部分)
- 面向对象 -- 继承和Java中的构造器
- Dream it possible
- 针对套接字关闭异常:Socket closed解决方案
- python--leetcode412. Fizz Buzz
- Caffe : Python中使用已有模型测试图像分类情况
- 接口测试之基础及简要验证清单
- BZOJ 3781 莫队 解题报告
- TFRecord预处理
- 【转】【修改】lisp-in-a-box配置
- 怎样安装Maven
- Js中的闭包与自执行函数
- Java集合框架