Skip to content

Commit 036660a

Browse files
authored
Add FizzBuzz logic building problem
Implement FizzBuzz function with input validation and examples.
1 parent c79034c commit 036660a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""FizzBuzz Problem.
2+
3+
This module contains a solution to the classic FizzBuzz problem.
4+
For numbers 1 to n, print 'Fizz' for multiples of 3, 'Buzz' for multiples of 5,
5+
and 'FizzBuzz' for multiples of both.
6+
"""
7+
8+
9+
def fizz_buzz(n: int) -> list[str]:
10+
"""
11+
Return a list of FizzBuzz results for numbers from 1 to n.
12+
13+
For each number from 1 to n:
14+
- Return 'FizzBuzz' if divisible by both 3 and 5
15+
- Return 'Fizz' if divisible by 3
16+
- Return 'Buzz' if divisible by 5
17+
- Return the number as a string otherwise
18+
19+
Args:
20+
n: Positive integer representing the range
21+
22+
Returns:
23+
A list of strings containing FizzBuzz results
24+
25+
Raises:
26+
ValueError: If n is not a positive integer
27+
28+
Examples:
29+
>>> fizz_buzz(5)
30+
['1', '2', 'Fizz', '4', 'Buzz']
31+
>>> fizz_buzz(15)
32+
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
33+
>>> fizz_buzz(0)
34+
Traceback (most recent call last):
35+
...
36+
ValueError: n must be a positive integer
37+
>>> fizz_buzz(-5)
38+
Traceback (most recent call last):
39+
...
40+
ValueError: n must be a positive integer
41+
"""
42+
if not isinstance(n, int) or n <= 0:
43+
raise ValueError("n must be a positive integer")
44+
45+
result = []
46+
for i in range(1, n + 1):
47+
if i % 15 == 0:
48+
result.append("FizzBuzz")
49+
elif i % 3 == 0:
50+
result.append("Fizz")
51+
elif i % 5 == 0:
52+
result.append("Buzz")
53+
else:
54+
result.append(str(i))
55+
return result
56+
57+
58+
if __name__ == "__main__":
59+
import doctest
60+
61+
doctest.testmod()

0 commit comments

Comments
 (0)