>>> import operator
>>> def add(it):
... return reduce(operator.add, it)
Ooh, I like this one. Thanks! 'hello' + 'world'
but not sum(['hello', 'world'])
Intuitively I would have expected the latter to be possible given the former but I guess it comes down to how the + operator and the sum function are implemented in Python, such that counter to my expectation sum is not a function that "applies the + operator" to it's arguments. The notion that this is how it should work stems from my impression that "sum" belongs to the same family as do "map", "reduce" and "apply" -- that these are somehow "functional" in nature in the sense that is observed in the Lisp family of languages. #!/usr/bin/env python3
# Word of factor
wof = { 3: 'Fizz', 5: 'Buzz', 7: 'Bar' }
def fizz (i):
out = ''.join([wof[k] for k in sorted(wof.keys()) if not(i % k)])
return out or str(i)
for i in range(1, 101):
print(fizz(i))
Some notes on my version: word for x, word in outputs
where our say wof[k] for k in sorted(wof.keys())
However, when I wrote mine I imagined myself sitting in front of an interactive interpreter session. wof[19] = 'Bazinga'
But let's pretend that yours was global as well outputs.append((19, 'Bazinga'))
So aside from the global / not global we are on equal ground thus far. wof[13] = 'Fnord'
Whereas if you did outputs.append((13, 'Fnord'))
then now you are out of order. out = ''.join([wof[k] for k in sorted(wof.keys()) if not(i % k)])
return out or str(i)
as opposed to your all-at-once return ''.join(word for x, word in outputs if i % x == 0) or str(i)
In my opinion splitting it exactly the way I did is more readable. Again, not a critique against what you wrote. Esp. since you said it yourself that your code was a bit tongue-in-cheek. out = ''.join([wof[k] for k in sorted(wof.keys()) if not(i % k)])
is all that nice either.
Unless global warming gets sufficiently bad, in which case that will be the worst damage.