News for hackers. Stuff that matters.
Re:Overthinking Fizzbuzz with Monoids by blixt on Thursday September 14, 2017 @10:08AM (#15248137)
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))

There are no comments on this comment yet.