Fizz Buzz Implementations in Python
The "Fizz-Buzz" coding challenge is used by a lot company, to filter out candidates how can not even write/think/implement a very simple conditional code block. I got this problem my interview few times. The first time, I took too long to write the code and the code as like a price of "shit".
The "Fizz-Buzz" coding problem is looks something like this.
"Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”."
I saw a lot of different way people solving this, here is there using Python. I like the second one most, it's elegant and easy to change but you have to be good with python to write/understand this.
First
Very simple 4 lines with only two if. Adding new condition like "if dividable by 4 print "buzzfizz"" is very easy, you just need to add another if with the condition.
for num in range (1, 101):
fizz = "" if num % 3 else "Fizz"
buzz = "" if num % 5 else "Buzz"
print fizz + buzz if fizz or buzz else num
Second
A clean and elegant version with only one if. Adding new condition like "if dividable by 4 print "buzzfizz"" is very very easy, you just need to add another entry on dictionary.
values = ((3, "Fizz"), (5, "Buzz"))
for n in range(1, 101):
res = ''.join(v for (k, v) in values if not n % k)
print(res if res else n)
Third
With three if it's most primitive version. Adding new condition like "if dividable by 4 print "buzzfizz"" is difficult then the other solution as you have to balance the the position of new condition with the existing one.
for fizzbuzz in range(100):
if fizzbuzz % 15 == 0:
print("FizzBuzz")
continue
elif fizzbuzz % 3 == 0:
print("Fizz")
continue
elif fizzbuzz % 5 == 0:
print("Buzz")
continue
print(fizzbuzz)