Algorithms · The shape of every puzzle
FizzBuzz
Count to n, but say Fizz, Buzz or FizzBuzz on the right numbers.
The problem
Count from 1 to n. For multiples of 3 say "Fizz", for multiples of 5 say "Buzz", for multiples of both say "FizzBuzz", and otherwise say the number. Return all the answers as a list of text.
fizz_buzz(3)→["1", "2", "Fizz"]fizz_buzz(5)→["1", "2", "Fizz", "4", "Buzz"]Now ask: what if there were a billion?
At a billion, the list of answers alone needs tens of gigabytes. Real systems don’t build the whole list: they hand out answers one at a time as they’re needed (a generator, yield in Python).
Aim for O(n)🌱 warm-up
Think it through
15 is a multiple of 3 and of 5. If you check “multiple of 3?” first, what does 15 say?
- “FizzBuzz”
- “Fizz”, and it never gets to FizzBuzz
Show the answer
“Fizz”, and it never gets to FizzBuzz. An if / elif chain stops at the first match. Put the most specific case (both, so multiple of 15) first. Order of checks is a bug that shows up everywhere, not just here.
How do you tell that a number divides by 3?
i / 3is a whole numberi % 3 == 0: nothing left over
Show the answer
i % 3 == 0: nothing left over. % gives the remainder. Remainder 0 means it divides evenly. You’ll use % for even/odd, wrapping around a circle, and spreading things across machines.
Stuck? 3 nudges, smallest first
i % 3 == 0is True whenidivides by 3 with nothing left over. That’s how you spot a multiple.- Check for 15 first. If you check 3 first, 15 says "Fizz" and never reaches "FizzBuzz".
- Inside the loop:
if i % 15 == 0→ "FizzBuzz",elif i % 3 == 0→ "Fizz",elif i % 5 == 0→ "Buzz",else→str(i).
The fast way
Try it yourself before you open this.
Show the fast version
def fizz_buzz(n):take a number n answers = []start an empty list of answers for i in range(1, n + 1):count from 1 up to n if i % 15 == 0:a multiple of both 3 and 5? answers.append("FizzBuzz")say FizzBuzz elif i % 3 == 0:a multiple of 3? answers.append("Fizz")say Fizz elif i % 5 == 0:a multiple of 5? answers.append("Buzz")say Buzz else:none of those answers.append(str(i))say the number return answershand back the listSolve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.