Fizz Buzz Program in Python

Hello Coderz, Welcome to codingbroz where we make programming easy and fun for you.

Today, I am going to discuss an amazing job interview problem in python. This is an important problem to know if you’re preparing for any coding interview no matter which position.

Fizz Buzz Program in Python

What is FizzBuzz ?

FizzBuzz is a very simple programming problem which is asked in software developer job interviews to determine whether the candidate knows to write code or not.

Now, you must be thinking if it is an easy problem then why is it asked in an interview ?

The answer to that is, Though the FizzBuzz problem is easy but how you approach and solve the problem makes all the difference. Interviewer determines whether the candidate is a good coder or not !

Let’s see what is the FizzBuzz problem : 

Write a program to print numbers from 1 to 100. But for multiples of 3 print  Fizz instead and for the multiple of 5 print Buzz and for the numbers multiple of both 3 and 5 print FizzBuzz. 

So, let’s see the codes to solve the FizzBuzz program in python.

Naive Solution : FizzBuzz in python 

for i in range(1,101) :
    if i % 15 == 0 : print("FizzBuzz")
    elif i % 3 == 0 : print("Fizz")
    elif i % 5 == 0 : print("Buzz")
    else : print(i)

This program gives the output :


So, this is the naive solution every programmer will give. But the problem with this code is that

 i % 15 == 0 is treated same as i % 3 == 0 && i % 5 == 0

Which means we are comparing the number i with 3 or 5 two times in the above code. 

Now, lets see what a good coder will code.

Good Solution : FizzBuzz in Python

for i in range(1,101) :
    ans = ""
    if i%3==0 : ans+="Fizz"
    if i%5==0 : ans+="Buzz"
    if ans == "" : print(i)
    else : print(ans)

So, by writing this code we can avoid checking the divisibility of 3 and 5 two times.

But, there is one more good approach which only few programmers implement which is the better approach.

As the above 2 solutions used the use of modulo % operator to check the visibility, but the use of modulo % operator is very expensive as compared to any other operator like +,-,* e.t.c. 

So, let’s see how to avoid using modulo % operator and what does a better programmer implement to solve the fizzbuzz problem.

Better Solution : FizzBuzz in python

c3 = 0
c5 = 0
for i in range(1,101) :
    if c3 == 3 : 
        c3 = 0
    if c5 == 5 : 
        c5 = 0
    if ans == "" : print(i)
    else : print(ans)

This code is the better way to solve the FizzBuzz problem without the use of modulo % operator as the use of % is an expensive approach.

Now, let’s see how to solve the fizzbuzz program in just one line using python.

FizzBuzz program in single line using python

for i in range(1, 101) :
   print("Fizz"*(i%3<1)+(i%5<1)*"Buzz" or i)

Using the above code in python you can solve the fizzbuzz problem in a single line !

Leave a Comment

Your email address will not be published.