FizzBuzz, as a list
Write fizzbuzz(n) that returns a list of strings for the numbers 1 to n. Multiples of 3 become "Fizz", multiples of 5 become "Buzz", multiples of both become "FizzBuzz", and everything else is the number as a string.
fizzbuzz(5)
# ["1", "2", "Fizz", "4", "Buzz"]
Show hint
Build the word by adding "Fizz" and "Buzz" separately. If the word is still empty, use the number.
Show solution
def fizzbuzz(n):
out = []
for i in range(1, n + 1):
word = ""
if i % 3 == 0:
word += "Fizz"
if i % 5 == 0:
word += "Buzz"
out.append(word or str(i))
return out
Building the word up avoids a separate check for 15, and word or str(i) falls back to the number when the word is empty. This version is easy to extend: adding "Bazz" for 7 is one more if.
Want a problem like this every day? See today's problem and keep a streak going.