There is a pretty common interview/beginner coding puzzle called “Fizz Buzz.” It’s conceptually not that difficult, but there are a lot of ways to do it, and I’m sure lots of people have strong opinions on the absolute best way to complete it. I thought I’d share a few answers here. Here’s the problem (or, at least, one if its variants).
List out the numbers from 1 to 100. If the number is a multiple of 3, print “Fizz.” If the number is a multiple of 5, print “Buzz.” If the number is a multiple of 3 and 5, print “FizzBuzz.” Otherwise, just print the number.
The Naive (Bluntest) Solution
This solution works, but there’s some efficiency things that we can do to clean up a few loose ends.
The Improved If-Then Solution
A little shorter, a little easier to read. Let’s keep going.
Less Ifs Solution
In my opinion, not better or clearer, but it has an interesting use of a dictionary which is kind of neat. From here, you can kind of get more and more into abstract solutions, but it kind of gets Rube Goldberg-ish, seeming like a lot of work for a simplish task. One more with a little functional pythonic twist.
I think this is my favorite. If you’ve got a fun solution that’s different than these, share it! firstname.lastname@example.org