FizzBuzz Solution (Python)

  • 0

    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.

      1. 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]
            for i in range(1,n+1):
                if i % 15==0: 
                elif i % 3==0:
                elif i % 5==0:
            return ans
      1. 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.
    • 2.1.
    def fizzBuzz(self, n):
        return['FizzBuzz'[i%-3&-4:i%-5&8^12]or`i`for i in range(1,n+1)]
    • 2.2.
    def fizzBuzz(self, n):
        return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.