Fizz Buzz? How trivial.
Recently, I needed to submit a fizz-buzz program as part of my application for a summer internship (hi Dagger Analytics!). I’ve decided to take advantage of that to talk about why sometimes, the most elegant code isn’t the best code.
Cutting to the chase
Here is my Fizz-Buzz code:
Click to Toggle Output
Post-mortem (the good part)
Ok, so now that you have viewed this solution, you may have some questions. I can hear them right now.
1 2 3 4 5 6 7 8 9 for i in range(1, 101): string = '' if i % 3 == 0: string += 'fizz' if i % 5 == 0: string += 'buzz if string == '': string = str(i) print(string)
As you can see, it’s the exact same thing. Alright, cool. So why didn’t I do something totally rad, like this list comprehension!?
1 2 for line in [str(i) if (i % 3 != 0 and i % 5 != 0) else 'fizz' if (i % 3 == 0) else 'buzz' if (i % 5 == 0) else 'fizzbuzz' for i in range(1, 101)]: print(line)
See, it’s only 2 lines and does the exact same thing! It also showcases my l33t h4x0r skills! Well, yeah, but you tell me what’s going on in that mess.
When writing code, especially when it’s a one-off sort of thing, it’s often easy to get stuck trying to get a more “elegant” solution. But I think it’s good to keep in mind that the technically superior solution is not necessarily the best solution. Sure, the list comprehension is arguably faster, but you shouldn’t sacrifice that for readability, especially at such small scales.
That’s not to say you shouldn’t try to write good, performant code, but instead you should focus on writing maintainable, bug-free code, which ends up being a much more valuable skill in the real world.