This is an easy problem. What we need to do is to check if a number i in ranges from 1 to n has the divisor 3 and 5.
There are many ways to realize it in Python.
- Use a loop containing condition languages. This is simple and understood by everyone. And below is my solution.
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ ans= for i in range(1,n+1): if i % 15==0: ans.append("FizzBuzz") elif i % 3==0: ans.append("Fizz") elif i % 5==0: ans.append("Buzz") else: ans.append(str(i)) return ans
- I also see some amazing short solutions in the Discuss forum. These guys are really masters! Below are solutions provided by @StefanPochmann. He only writes one line. These short solutions cannot be realized without the convenience and flexibility of Python.
def fizzBuzz(self, n): return['FizzBuzz'[i%-3&-4:i%-5&8^12]or`i`for i in range(1,n+1)]
def fizzBuzz(self, n): return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]