FizzBuzz

My co-worker mentioned that “Fizz Buzz” is a common exercise in developer job interviews and many people struggle to solve it in time.

According to the web it is a popular kid’s game which aims at teaching division by some simple rules (see wikipedia):

Since it was new to me I decided to take a shot at it.

The rules are as follows:

  • Count numbers starting from 1
  • Say the number out loud unless one of the following rules is applicable
    • Number divisible by 3, say “fizz” instead
    • Number divisible by 5, say “buzz” instead
    • Number divisible by both, say “fizz buzz” instead

We can directly transform there rules into tests. Let’s use pytest to that end.

First we want to have a single check with a single value for each of the rules.

This makes it clear, that we need to make sure that “Fizz Buzz” takes precedence over “Fizz” and “Buzz”.

We will add some kind of approval testing based on the values in the wiki for the sake of completeness.

Based on this we can easily derive our implementation of “Fizz Buzz”.

By using an ordered iterable, namely a tuple, and returning the result for the very first match, we can be certain that our implementation tests for both, three and five, before checking each of them individually. If none of the rules is applicable the given number is returned instead.

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.