方法1:
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
list = []
for i in range(1,n+1):
if (i%3==0)&(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 list
Sol = Solution()
print Sol.fizzBuzz(15)
方法2:
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]
0,第二个算法是间接高效的算法
1,方法1是个人写的,没有什么特别的地方,主要需要注意的是在使用列表时,应该先定义一个空的列表,然后才能进行append等操作,否则会出错
2,方法2比较简洁,首先,字符串可以乘以一个数字或者布尔常量,就像(not i%3)当i时3的倍数时,i%3为0,not 0 则为True,则’Fizz’ * (not i % 3)为’Fizz’,很有趣的方法。
还有,字符串可以通过+的方法来对字符串进行连接。最后,str(int)将int型的变量转化为str