I thought I’d post a follow-up to yesterday’s FizzBuzz post with some sample solutions, as a bunch of you seemed to find it fun to solve. Feel free to add your own solutions in the comments of this post!
My own first solution was Python-based, and a fairly simple one:
for i in range(1,101):
if i % 3 == 0 and i % 5 == 0:
print "FizzBuzz"
elif i % 3 == 0:
print "Fizz"
elif i % 5 == 0:
print "Buzz"
else:
print i
Obviously it’s not in a function or anything, but I just wanted to do it as fast as possible. Shortly afterwards, I realised that line 2 could be simplified by changing it to:
if i % 15 == 0:
Because of course, if a number is a multiple of 3 and 5, then it must be a multiple of 15.
Here are a couple of nice alternatives (ideas courtesy of Dave, although re-written by me because we didn’t save them). First, writing FizzBuzz as a iterator:
def fizzbuzz_generator(n):
for i in range(1, n+1):
if i % 15 == 0:
yield "FizzBuzz"
elif i % 3 == 0:
yield "Fizz"
elif i % 5 == 0:
yield "Buzz"
else:
yield str(i)
for result in fizzbuzz_generator(100): print result
Then, a simple function to calculate the correct fizz/buzz, combined with a list comprehension to create the result (man, I love list comprehensions):
def fizzbuzz(i):
if i % 15 == 0:
return "FizzBuzz"
elif i % 3 == 0:
return "Fizz"
elif i % 5 == 0:
return "Buzz"
else:
return str(i)
print "\n".join([fizzbuzz(i) for i in range(1,101)])
Finally, here are two neat little Ruby one-liners, taken from the comments of the original FizzBuzz article. I hope the authors (Brendan, and Brian respectively) don’t mind me reproducing them here:
puts (1..100).map{|i|(s=(i%3==0?'Fizz':'')+(i%5==0?'Buzz':''))==''?i:s}
puts (1..100).map{|i|i%15==0?'FizzBuzz':i%5==0?'Buzz':i%3==0?'Fizz':i}
How neat is that? Anyway, as I said, feel free to leave your own solutions below.