3 ms·
Sorry it wasn't meant very seriously, just me expressing a caricature of idiomatic Python :) So disclaimer: good old `for` loops are often a better choice unle
by blixt 9y ago
Sorry it wasn't meant very seriously, just me expressing a caricature of idiomatic Python :)
So disclaimer: good old `for` loops are often a better choice unless you're doing a simple modification or filtering of another sequence.
- svara 9y agoReally? 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()).
- blixt 9y agoI 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))
- paultopia 9y agoHeh, I actually like blixt's solution better than mine too. :-)