S1Q1 · Describe Number Based on Divisibility¶
⚡ Quick Reference
Function: describe_number(num: int) -> str
Core idea: check divisibility by 15 first, then 3, then 5, then default to "Normal".
def describe_number(num: int) -> str:
if num % 15 == 0:
return "FizzBuzz"
elif num % 3 == 0:
return "Fizz"
elif num % 5 == 0:
return "Buzz"
return "Normal"
Key rules:
- Check % 15 before % 3 and % 5 -otherwise FizzBuzz cases get caught early
- Exactly one of the four strings is returned
- The classic FizzBuzz problem -appears constantly in interviews
Problem Statement¶
Problem
Write a function describe_number(num) that returns "FizzBuzz" if divisible by both 3 and 5, "Fizz" if by 3 only, "Buzz" if by 5 only, and "Normal" otherwise.
Examples:
9
"Fizz"
10
"Buzz"
15
"FizzBuzz"
7
"Normal"
Understanding the problem¶
num |
% 3 == 0 |
% 5 == 0 |
Result |
|---|---|---|---|
| 9 | ✅ | ❌ | "Fizz" |
| 10 | ❌ | ✅ | "Buzz" |
| 15 | ✅ | ✅ | "FizzBuzz" |
| 7 | ❌ | ❌ | "Normal" |
Why check % 15 first?
15 is divisible by both 3 and 5. If you check % 3 first, 15 would return "Fizz" before reaching the % 5 check. Checking % 15 first ensures the combined case is caught correctly.
Solution approaches¶
def describe_number(num: int) -> str:
result = ""
if num % 3 == 0:
result += "Fizz"
if num % 5 == 0:
result += "Buzz"
return result if result else "Normal"
Build the result by concatenating -no need to check % 15 separately. Both strings get appended in the right order automatically when both conditions are true.
Key takeaways¶
Check the combined case first
Always check % 15 (or % 3 and % 5) before the individual checks. Getting this order wrong is the most common FizzBuzz mistake in interviews.
String concatenation avoids % 15
The concatenation approach naturally handles the combined case -both strings get appended when both conditions are true, producing "FizzBuzz" automatically.
Boolean tuple as dict key
(num % 3 == 0, num % 5 == 0) produces a tuple of booleans mapping cleanly to all four outcomes. A neat pattern for multi-condition dispatch.