Fizz Buzz in Python



Suppose we have a number n. We have to display a string representation of all numbers from 1 to n, but there are some constraints.

  • If the number is divisible by 3, write Fizz instead of the number
  • If the number is divisible by 5, write Buzz instead of the number
  • If the number is divisible by 3 and 5 both, write FizzBuzz instead of the number

To solve this, we will follow these steps −

  • For all number from 1 to n,
    • if a number is divisible by 3 and 5 both, print “FizzBuzz”
    • otherwise when the number is divisible by 3, print “Fizz”
    • otherwise when the number is divisible by 5, print “Buzz”
    • otherwise, write the number as a string

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def fizzBuzz(self, n):
      """
      :type n: int
      :rtype: List[str]
      """
      result = []
      for i in range(1,n+1):
         if i% 3== 0 and i%5==0:
            result.append("FizzBuzz")
         elif i %3==0:
            result.append("Fizz")
         elif i% 5 == 0:
            result.append("Buzz")
         else:
            result.append(str(i))
      return result
ob1 = Solution()
print(ob1.fizzBuzz(30))

Input

30

Output

["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz",
"13","14","FizzBuzz","16","17","Fizz","19","Buzz","Fizz","22","23",
"Fizz","Buzz","26","Fizz","28","29","FizzBuzz"]

Advertisements