Thursday, January 3, 2013

One Line Fizz Buzz Test in Python

Here it is (in all its ugliness):

print '\n'.join("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i) for i in range(1,101))

Python is pretty astounding. This little bugger was easy to code, it is somewhat readable, and it is even understandable. Pretty cool, eh?

Short explanation:
  • '\n'.join(...)
    Every item generated in the join function will be on its own line
  • for i in range(1,101)
    Loop from 1 to 101, giving i the value of each
  • "Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i)
    If i is divisible by 3 then keep "Fizz", do the same for "Buzz" with 5. Add the kept values together. Or it will simply output i as a string if it fails to get "Fizz" or "Buzz"

No comments:

Post a Comment