Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Really? I actually liked that solution, I think it's both readable and clever. The rule priority is defined by the order of your list of tuples ('fizzbuzz' vs. 'buzzfizz'), so easy to change. That's superior to the solution above with sorted(outputs.keys()).


I would say my solution is borderline. It requires maybe one or two extra reads to grok in its entirety due to multiple conditionals, one of which is in a loop and the other outside. Here's a more readable version for someone looking at it the first time, or who is not too used to Python:

    OUTPUTS = [(3, 'Fizz'), (5, 'Buzz'), (7, 'Bar')]
    def fizzbuzz(i):
      result = ''
      for x, word in OUTPUTS:
        if i % x == 0:
          result += word
      return result or str(i)
Even the final `or` could be broken out to an `if not`, but in this case it's so simple I prefer putting it together, much like a coalescing operator.

And then for shits and giggles we can say screw it and put it all in one line:

    print '\n'.join(''.join(word for x, word in [(3, 'Fizz'), (5, 'Buzz'), (7, 'Bar')] if i % x == 0) or str(i) for i in xrange(1, 101))


Heh, I actually like blixt's solution better than mine too. :-)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: