Here is one possible implementation of an extensible and readable FizzBuzz function in Python:
code
def fizzbuzz(n, fizz=3, buzz=5, fizz_str="Fizz", buzz_str="Buzz"):
"""
Prints numbers from 1 to n, replacing multiples of fizz with fizz_str,
multiples of buzz with buzz_str, and multiples of both with fizz_str + buzz_str.
"""
for i in range(1, n+1):
if i % fizz == 0 and i % buzz == 0:
print(fizz_str + buzz_str)
elif i % fizz == 0:
print(fizz_str)
elif i % buzz == 0:
print(buzz_str)
else:
print(i)
This implementation takes an optional fizz and buzz parameter, as well as optional fizz_str and buzz_str parameters, which allows for customization of the behavior of the function.
The function uses a for loop to iterate over the numbers 1 to n, and uses an if-elif-else statement to check if the current number is divisible by fizz and/or buzz. Depending on the result of these checks, the function either prints fizz_str, buzz_str, fizz_str + buzz_str, or the number itself.
This implementation is also readable because it uses clear variable names, includes a docstring to explain its purpose and behavior, and uses whitespace to make the code easy to read and understand.
Here is an example of how the function can be used:
code
# Print the numbers 1 to 15, replacing multiples of 3 with "Fizz" and multiples of 5 with "Buzz"
fizzbuzz(15)
# Print the numbers 1 to 20, replacing multiples of 7 with "Fizz" and multiples of 11 with "Buzz"
fizzbuzz(20, fizz=7, buzz=11, fizz_str="Fizz", buzz_str="Buzz")
# Print the numbers 1 to 30, replacing multiples of 2 with "Even" and multiples of 3 with "Odd"
fizzbuzz(30, fizz=2, buzz=3, fizz_str="Even", buzz_str="Odd")
Note: This implementation is not the most efficient one, but it is simple, readable and extensible. If you need a more efficient solution, you can use the modulo operator % in a more strategic way to avoid unnecessary calculations. For example:
code
def fizzbuzz(n, fizz=3, buzz=5, fizz_str="Fizz", buzz_str="Buzz"):
"""
Prints numbers from 1 to n, replacing multiples of fizz with fizz_str,
multiples of buzz with buzz_str, and multiples of both with fizz_str + buzz_str.
"""
for i in range(1, n+1):
output = ""
if i % fizz == 0:
output += fizz_str
if i % buzz == 0:
output += buzz_str
if not output:
output = str(i)
print(output)
This implementation uses less modulo evaluations, as it only evaluates i % fizz and i % buzz once per iteration, and only if the previous check passed.
Also, you can use tuple unpacking to make the function signature more readable and easier to use.
code
def fizzbuzz(n, *args, **kwargs):
"""
Prints numbers from 1 to n, replacing multiples of fizz with fizz_str,
multiples of buzz with buzz_str, and multiples of both with fizz_str + buzz_str.
"""
fizz, buzz, fizz_str, buzz_str = args + (3, 5, "Fizz", "Buzz")
for i in range(1, n+1):
output = ""
if i % fizz == 0:
output += f