FizzBuzz

By Monty, 16th April 2015

FizzBuzzThis 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”.

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=' ')

Alternatively:

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=' ')

Or:

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

See Rosettacode.

Wikipedia:

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".

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:

def funny_func(x):

    if (dbLookUp(x) == True):

        result = True

    elif (dbLookUp(x) == False):

        result = False

    return result

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!

What do you think?

Leave a Reply

%d bloggers like this: