Fizzbuzz Without Ifs in 90 Characters -- I'll Buy You a Beer if You Can Beat It
Join the DZone community and get the full member experience.
Join For Freeyesterday i got nerd-sniped into solving the fizzbuzz problem without using if sentences.
fizzbuzz, no ifs: [{0: "fizzbuzz"}.get(x%(3*5), {0: "fizz"}.get(x%3, {0: "buzz"}.get(x%5))) for x in range(3, 100, 3)+range(5, 105, 5)]
— swizec (@swizec) september 16, 2012
unfortunately, a more careful inspection of the problem specification reveals this solution was incorrect.
write a program that prints the numbers from 1 to 100. but for multiples of three print “fizz” instead of the number and for the multiples of five print “buzz”. for numbers which are multiples of both three and five print “fizzbuzz”.
luckily, that’s a very simple fix:
# codegolf version (90 characters): [{0:"fizzbuzz"}.get(x%(3*5),{0:"fizz"}.get(x%3,{0:"buzz"}.get(x%5,x)))for x in range(101)] # slightly more readable: [{0: "fizzbuzz"}.get(x%(3*5), {0: "fizz"}.get(x%3, {0: "buzz"}.get(x%5, x))) for x in range(101)]
there you have it, a solution to the fizzbuzz problem that relies on python’s interactive command line interpreter thingy to do the printing, shaving off 4 characters for print .
the “trick”, if it can be called that, is relying on the native get method to return the correct string or fall back to the default value, which checks for the next string in the if-then-else chain.
i wish never to see code like that in something i have to maintain. ever.
the challenge
your challenge, should you choose to accept it, is to produce a shorter fizzbuzz solution without using if sentences. i will buy a bottle of beer for the winner.
the best scala solution so far is 106 characters, by @hairyfotr:
1 to 100 map(a=>println((a%3,a%5)match{case(0,0)=>"fizzbuzz"case(0,_)=>"fizz"case(_,0)=>"buzz"case _=>a})) /cc
no really, i will send a bottle of beer anywhere in the world if you write a shorter solution. of course, if feasible, i would prefer to take you out for a beer than use snail mail
Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Getting Started With the YugabyteDB Managed REST API
-
Merge GraphQL Schemas Using Apollo Server and Koa
-
Implementing a Serverless DevOps Pipeline With AWS Lambda and CodePipeline
-
Operator Overloading in Java
Comments