📅  最后修改于: 2023-12-03 15:15:05.520000             🧑  作者: Mango
FizzBuzz is a classic coding interview question that is commonly used to evaluate a programmer's basic programming skills. It is a simple program that prints numbers from 1 to N, replacing numbers divisible by 3 with "Fizz", numbers divisible by 5 with "Buzz", and numbers divisible by both 3 and 5 with "FizzBuzz".
Here is a Python implementation of the FizzBuzz problem:
def fizzbuzz(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 fizzbuzz function
n = 20
output = fizzbuzz(n)
print(output)
The function fizzbuzz(n)
takes an integer n
as input and returns a list of strings. It iterates from 1 to n
and checks each number for divisibility by 3, 5, or both. Depending on the divisibility, it adds the corresponding string to the list result
.
In the given example, the fizzbuzz
function is called with n = 20
. The output is then printed, showing the FizzBuzz sequence from 1 to 20: ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz']
.
This implementation can be easily extended to handle larger ranges by changing the value of n
. Additionally, you can modify the FizzBuzz rules or add more rules by modifying the conditions in the if
statements.
Remember to run the code in a Python environment to see the output.