jameswfrost.co.uk

home about archive

FizzBuzz Follow-up

May 30 2008

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:

1 for i in range(1,101):
2     if i % 3 == 0 and i % 5 == 0:
3         print "FizzBuzz"
4     elif i % 3 == 0:
5         print "Fizz"
6     elif i % 5 == 0:
7         print "Buzz"
8     else:
9         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:

 1 def fizzbuzz_generator(n):
 2     for i in range(1, n+1):
 3         if i % 15 == 0:
 4             yield "FizzBuzz"
 5         elif i % 3 == 0:
 6             yield "Fizz"
 7         elif i % 5 == 0:
 8             yield "Buzz"
 9         else:
10             yield str(i)
11 
12 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):

 1 def fizzbuzz(i):
 2     if i % 15 == 0:
 3         return "FizzBuzz"
 4     elif i % 3 == 0:
 5         return "Fizz"
 6     elif i % 5 == 0:
 7         return "Buzz"
 8     else:
 9         return str(i)
10 
11 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.

blog comments powered by Disqus