Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Fizz Buzz in Python
The Fizz Buzz problem is a classic programming challenge where we replace numbers with specific strings based on divisibility rules. For numbers from 1 to n, we print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
Problem Rules
- If the number is divisible by 3, write "Fizz" instead of the number
- If the number is divisible by 5, write "Buzz" instead of the number
- If the number is divisible by both 3 and 5, write "FizzBuzz" instead of the number
- Otherwise, write the number as a string
Solution Approach
We iterate through numbers from 1 to n and check divisibility conditions in this order ?
- First check if divisible by both 3 and 5 (15) − print "FizzBuzz"
- Then check if divisible by 3 − print "Fizz"
- Then check if divisible by 5 − print "Buzz"
- Otherwise − print the number as string
Using Class-Based Approach
class Solution:
def fizzBuzz(self, n):
result = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
# Test the solution
solution = Solution()
print(solution.fizzBuzz(15))
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
Using Simple Function
def fizz_buzz(n):
result = []
for i in range(1, n + 1):
if i % 15 == 0: # Divisible by both 3 and 5
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
# Test with n=20
print(fizz_buzz(20))
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz']
Using String Concatenation
An alternative approach uses string concatenation to build the result ?
def fizz_buzz_concat(n):
result = []
for i in range(1, n + 1):
output = ""
if i % 3 == 0:
output += "Fizz"
if i % 5 == 0:
output += "Buzz"
result.append(output if output else str(i))
return result
# Test the function
print(fizz_buzz_concat(10))
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz']
Comparison of Approaches
| Method | Readability | Extensibility | Best For |
|---|---|---|---|
| Explicit conditions | High | Low | Simple cases |
| Modulo 15 check | Medium | Low | Performance |
| String concatenation | High | High | Adding more rules |
Conclusion
The Fizz Buzz problem demonstrates basic conditional logic and modular arithmetic. The string concatenation approach is most flexible for extending to additional divisibility rules, while explicit conditions offer the clearest logic flow.
Advertisements
