Programming Interviews: Fizz Buzz

An all-time programming classic for interviews

Martin Thoma

--

Photo by Christina @ wocintechchat.com on Unsplash

When companies interview potential new software developers, they typically also have a programming interview to make sure that the candidate can actually write very simple programs. Fizz Buzz is a very simple classical example. The problem is easy to describe and the solution is easy as well.

Problem Statement

Write a function that takes an integer and returns a string. If the number is divisible by 3, return “Fizz”. If the number is divisible by 5, return “Buzz”. If the number is divisible by 15, return “Fizz Buzz”. If the number is not divisible by 3 nor by 5, return the number itself.

Solution

In Python, a solution looks like this:

def fizzbuzz(number: int) -> str:
if number % 15 == 0:
return "Fizz Buzz"
if number % 3 == 0:
return "Fizz"
if number % 5 == 0:
return "Buzz"
return str(number)

Unit Tests

Seeing which cases people test gives a good indicator of how used they are to testing at all. There are two groups of tests I want to see:

  • Typical Cases
  • Edge Cases

In Python, you can use Pytest to run the following tests:

from fizzbuzz import fizzbuzzdef test_3():
assert fizzbuzz(3) == "Fizz"
assert fizzbuzz(6) == "Fizz"
assert fizzbuzz(9) == "Fizz"
assert fizzbuzz(12) == "Fizz"
def test_5():
assert fizzbuzz(5) == "Buzz"
assert fizzbuzz(10) == "Buzz"
assert fizzbuzz(20) == "Buzz"
def test_15():
assert fizzbuzz(15) == "Fizz Buzz"
assert fizzbuzz(30) == "Fizz Buzz"
assert fizzbuzz(45) == "Fizz Buzz"
def test_number():
assert fizzbuzz(1) == "1"
assert fizzbuzz(2) == "2"
def test_edge_cases():
assert fizzbuzz(-1) == "-1"
assert fizzbuzz(3 ** 20) == "Fizz"
assert fizzbuzz(-(3 ** 20)) == "Fizz"
assert fizzbuzz(0) == "Fizz Buzz"

Extensions

--

--

Martin Thoma

I’m a Software Engineer with over 10 years of Python experience (Backend/ML/AI). Support me via https://martinthoma.medium.com/membership