412. Fizz Buzz
On LeetCode ->Reformulated question¶
Return a list of strings for numbers 1..n:
"FizzBuzz"if the number is divisible by15"Fizz"if divisible by3"Buzz"if divisible by5- otherwise the number itself as a string
Compact example:
n = 6 -> ["1", "2", "Fizz", "4", "Buzz", "Fizz"]
Key trick¶
Check the combined case first:
- divisibility by
15 - then
3 - then
5
This avoids incorrectly returning "Fizz" or "Buzz" for multiples of both.
Trap¶
Common mistakes:
- checking
3and5before15 - using
0..n-1instead of1..n - returning integers instead of strings
Why this question is interesting¶
It is simple but tests:
- careful condition ordering
- off-by-one handling
- clean loop and string construction
Solve the problem with idiomatic python¶
class Solution:
def fizzBuzz(self, n: int) -> list[str]:
answer = []
# Build the result from 1 to n inclusive.
for i in range(1, n + 1):
if i % 15 == 0:
answer.append("FizzBuzz")
elif i % 3 == 0:
answer.append("Fizz")
elif i % 5 == 0:
answer.append("Buzz")
else:
answer.append(str(i))
return answer
Library alternative:
- None worth using here; the direct loop is the exact intended solution.
Pytest test¶
import pytest
@pytest.mark.parametrize(
("n", "expected"),
[
(1, ["1"]),
(3, ["1", "2", "Fizz"]),
(5, ["1", "2", "Fizz", "4", "Buzz"]),
(15, [
"1", "2", "Fizz", "4", "Buzz",
"Fizz", "7", "8", "Fizz", "Buzz",
"11", "Fizz", "13", "14", "FizzBuzz",
]),
(16, [
"1", "2", "Fizz", "4", "Buzz",
"Fizz", "7", "8", "Fizz", "Buzz",
"11", "Fizz", "13", "14", "FizzBuzz", "16",
]),
],
)
def test_fizz_buzz(n, expected):
assert Solution().fizzBuzz(n) == expected
Comment my solution¶
- No solution was provided to review.
Code¶
import pytest
class Solution:
def fizzBuzz(self, n: int) -> list[str]:
answer = []
# Build the result from 1 to n inclusive.
for i in range(1, n + 1):
if i % 15 == 0:
answer.append("FizzBuzz")
elif i % 3 == 0:
answer.append("Fizz")
elif i % 5 == 0:
answer.append("Buzz")
else:
answer.append(str(i))
return answer
@pytest.mark.parametrize(
("n", "expected"),
[
(1, ["1"]),
(3, ["1", "2", "Fizz"]),
(5, ["1", "2", "Fizz", "4", "Buzz"]),
(15, [
"1", "2", "Fizz", "4", "Buzz",
"Fizz", "7", "8", "Fizz", "Buzz",
"11", "Fizz", "13", "14", "FizzBuzz",
]),
(16, [
"1", "2", "Fizz", "4", "Buzz",
"Fizz", "7", "8", "Fizz", "Buzz",
"11", "Fizz", "13", "14", "FizzBuzz", "16",
]),
],
)
def test_fizz_buzz(n, expected):
assert Solution().fizzBuzz(n) == expected
Solution().fizzBuzz(3)
Solution().fizzBuzz(5)
Solution().fizzBuzz(15)