Fizz Buzz

Fizz Buzz? How triv­ial.

Recently, I needed to sub­mit a fizz-buzz pro­gram as part of my ap­pli­ca­tion for a sum­mer in­tern­ship (hi Dagger Analytics!). I’ve de­cided to take ad­van­tage of that to talk about why some­times, the most el­e­gant code is­n’t the best code.

Cutting to the chase

Here is my Fizz-Buzz code:

// Javascript solution

for(let i = 1; i < 101; i++) {
   let string = '';
   if (i % 3 === 0) {
      string += 'fizz';
   }
   if (i % 5 === 0) {
      string += 'buzz';
   }
   if (string === '') {
      string = parseInt(i);
   }
   console.log(string)
}

Click to Toggle Output

Post-mortem (the good part)

Ok, so now that you have viewed this so­lu­tion, you may have some ques­tions. I can hear them right now.

Naitian, why would you use Javascript? Why are you us­ing 13 lines to write some­thing this sim­ple? Etc, etc.

Well to ad­dress the ele­phant in the room, I used Javascript be­cause it was the most con­ve­nient thing for me to write in. But to sat­isfy you, here’s a so­lu­tion in Python.

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 ex­act same thing. Alright, cool. So why did­n’t I do some­thing to­tally rad, like this list com­pre­hen­sion!?

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 ex­act same thing! It also show­cases my l33t h4x0r skills! Well, yeah, but you tell me what’s go­ing on in that mess.

When writ­ing code, es­pe­cially when it’s a one-off sort of thing, it’s of­ten easy to get stuck try­ing to get a more elegant” so­lu­tion. But I think it’s good to keep in mind that the tech­ni­cally su­pe­rior so­lu­tion is not nec­es­sar­ily the best so­lu­tion. Sure, the list com­pre­hen­sion is ar­guably faster, but you should­n’t sac­ri­fice that for read­abil­ity, es­pe­cially at such small scales.

That’s not to say you should­n’t try to write good, per­for­mant code, but in­stead you should fo­cus on writ­ing main­tain­able, bug-free code, which ends up be­ing a much more valu­able skill in the real world.