FizzBuzz¶
The classic screening problem, simple on the surface, but it tests whether you can translate branching logic into clean code without off-by-one mistakes.
Problem¶
Print the numbers from 1 to n, but replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".
Input: an integer n
Output: printed sequence with the substitution rules applied
Approach¶
The only subtlety is ordering the checks correctly. If you test % 3 and % 5 before % 15, you'll never reach the combined case. Check the most specific condition first:
i % 15 == 0, divisible by both 3 and 5, print"FizzBuzz"i % 3 == 0, print"Fizz"i % 5 == 0, print"Buzz"- Otherwise, print the number itself
This is the same pattern you see in rule-based feature preprocessing: evaluate the most restrictive rule first so it isn't shadowed by a more general one.
Implementation¶
def fizz_buzz(n):
for i in range(1, n + 1):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
if __name__ == "__main__":
fizz_buzz(20)
Complexity¶
- Time: O(n)
- Space: O(1)
Takeaway¶
FizzBuzz is trivial algorithmically, but it's a good reminder that rule ordering matters, in inference pipelines and business-logic layers alike, the most specific rule should always be evaluated first.