by JackC · 12y ago · 0 comments
FIZZ=3
BUZZ=5
cache = {}
for i in range(FIZZ-1, FIZZ*BUZZ, FIZZ):
cache[i] = 'Fizz'
for i in range(BUZZ-1, FIZZ*BUZZ, BUZZ):
try:
cache[i] += 'Buzz'
except KeyError:
cache[i] = 'Buzz'
for i in range(100):
try:
print cache[i%(FIZZ*BUZZ)]
except KeyError:
print i+1
[1] https://docs.python.org/2/glossary.html#term-eafpA generator version:
from itertools import izip, islice
def fizzes():
i=0
while True:
yield '' if i%3 else 'Fizz'
i += 1
def buzzes():
i=0
while True:
yield '' if i%5 else 'Buzz'
i += 1
def numbers():
i=0
while True:
yield str(i+1) if i%3 and i%5 else ''
i += 1
print "\n".join("".join(parts) for parts in islice(izip(fizzes(), buzzes(), numbers()), 100)) 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. 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