Alan Richmond

FizzBuzz

This is apparently a well-known interview question (but not one I was ever asked). Print the numbers 1 to 100, but replace every number divisible by 3 with “Fizz”, every number divisible by 5 with “Buzz”, and every number that’s divisible by both 3 & 5 with “FizzBuzz”. Apparently many people have difficulty with it. Really?

Fizz buzz is a group word game for children to teach them about division. Players take turns to count incrementally, replacing any number divisible by three with the word “fizz”, and any number divisible by five with the word “buzz”.

[python] for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz", end=’ ‘)
elif i % 3 == 0:
print("Fizz", end=’ ‘)
elif i % 5 == 0:
print("Buzz", end=’ ‘)
else:
print(i, end=’ ‘)
[/python]

Alternatively:

[python] for i in range(1, 101):
s = ”
if i % 3 == 0:
s += "Fizz"
if i % 5 == 0:
s += "Buzz"
if s == ”:
s += str(i)
print(s, end=’ ‘)
[/python]

Or:

[python] for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i, end=’ ‘)
[/python]

See Rosettacode.

[welcomewikilite wikiurl=”https://en.wikipedia.org/wiki/Fizz_buzz” sections=”Short description” settings=””]

Sometime programmers just can’t program, or when they do, they screw up badly. Here’s a piece of code I found when I worked at the Space Telescope Science Institute (before Hubble was launched). It was in Fortran, and the details may have been slightly different, but the essential horror is captured in this Python translation:

[python] def funny_func(x):

if (dbLookUp(x) == True):

result = True

elif (dbLookUp(x) == False):

result = False

return result
[/python]

This is bad on several levels, and if you can’t reduce this to one line… May I humbly suggest to any recruiters who like giving the FizzBuzz test that asking candidates for programming jobs to simplify funny_func might also be revealing!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.