This post regarding the highly overused interview question dubbed the “Fizzbuzz” problem made me chuckle. Not sure why the java runner isn’t encapsulated in a factory though. Never know what other runners you may want to run someday. A runnerfactory would defiantly fill that void and really enhance the enterprise value-add of the solution thereby increasing the synergy of all teams involved.

Java jokes aside. Where’s the abuse of format/generator solution? I’m not going to call this solution a one liner, because it’s not < 80 chars. In fact I'd really like it if everyone would use that as the golden standard of "one-liner". Newlines notwithstanding, if it doesn't fit on a single line in the terminal it's not a one-liner.

Now that we got that out of the way. Fizzbuzz. For those who don't know, the problem is described as such:

For the numbers from 1-100, if it is divisible by 3, print “Fizz”. 
If it is divisible by 5, print “Buzz”. 
However, if it is divisible by both 3 and 5, then print “Fizzbuzz”.

It’s not a particularly difficult problem, it’s usually moreso just to see what your programming style is like, what language you prefer, etc. Anywho, here’s my crack at it; which isn’t a one-liner, but it’s close (single statement anyway).

    "fizz" * int(not i % 3),
    "buzz" * int(not i % 5),
    ).title() or str(i) for i in range(1, 101)])

And although I am in agreement with his Pythonic solution mentioned first, and that’s more than likely the way I’d write this if I had to test it and deploy it in production, the generator->print way is faster. I’m guessing this is due to calling print less; it does more in memory, less IO usage. It’s interesting how much the gap increases when you move into python3-land (although that could be for a variety of reasons).

Numbers! I ran the demos with timeit, with 10000 iterations of each. Bunch of different python versions, running native on a crappy old laptop. (for the < 2.7 versions I swapped out .format() for old style string concatenation)

mine * 10000 = 9.81940484047 vs his * 10000 = 10.0548670292

mine * 10000 = 8.99658203125 vs his * 10000 = 9.72375297546

mine * 10000 = 9.43055009842 vs his * 10000 = 9.59376788139

mine * 10000 = 8.341217994689941 vs his * 10000 = 18.619366884231567

mine * 10000 = 9.594497313999454 vs his * 10000 = 19.601987035988714

mine * 10000 = 9.539193375007017 vs his * 10000 = 18.340404470000067

tl;dr: Readability is often times a trade-off with performance. Profile the functions you write if speed is important (and/or use a faster language if it’s really crucial)

Leave a Reply

Your email address will not be published. Required fields are marked *