Re:Unpythonic Python
by binarycrusader on Wednesday April 09, 2014 @03:55PM
(#7561916)
Or better yet, don't even bother asking for forgiveness or permission:
from collections import defaultdict
FIZZ=3
BUZZ=5
cache = defaultdict(str)
for i in xrange(FIZZ-1, FIZZ*BUZZ, FIZZ):
cache[i] = 'Fizz'
for i in xrange(BUZZ-1, FIZZ*BUZZ, BUZZ):
cache[i] += 'Buzz'
for i in xrange(100):
print cache.get(i%(FIZZ*BUZZ), i+1)
But I'm rather partial to the generator versions you and others posted.I like these. Another generator version:
def fbgen(text, divisor):
while True:
for i in range(1, divisor):
yield ""
yield text
def derrangedBuzz(max):
fizzer = fbgen("Fizz", 3)
buzzer = fbgen("Buzz", 5)
for i in range(1, max + 1):
s = fizzer.next() + buzzer.next()
if s == "":
print i
else:
print s
A generator version: