General FizzBuzz: Difference between revisions

Content added Content deleted
m (→‎{{header|Python}}: Corrected mistake.)
(→‎{{header|Python}}: Modified second example to use a generator; added another example.)
Line 1,483: Line 1,483:




'''Alternative version using counters instead of modulo'''
'''Alternative version - generator using counters instead of modulo'''
{{works with|Python|3.x}}
{{works with|Python|3.x}}
<lang Python>n = 100
<lang Python>n = 100
Line 1,492: Line 1,492:


def fizzbuzz(n=n, mods=mods):
def fizzbuzz(n=n, mods=mods):
res = ''
cnts = {k:0 for k in mods.keys()}
cnts = {k:0 for k in mods.keys()}


for i in range(1,n+1):
for i in range(1,n+1):
wr = False
res = ''
for k,v in cnts.items():
for k,v in cnts.items():
v += 1
v += 1
Line 1,502: Line 1,501:
v = 0
v = 0
res += mods[k]
res += mods[k]
wr = True
cnts[k] = v
cnts[k] = v
yield res or str(i)

if not wr:
res += str(i)
res += '\n'

return res



if __name__ == '__main__':
if __name__ == '__main__':
n = int(input())
n = int(input())
mods = { int(k): v for k,v in (input().split(maxsplit=1) for _ in range(3)) }
mods = { int(k): v for k,v in (input().split(maxsplit=1) for _ in range(3)) }
print(fizzbuzz(n, mods))
for line in fizzbuzz(n, mods):
print(line)
</lang>

'''Another version, using ranges with step 3, 5, etc.'''
<lang Python>from collections import defaultdict

def fizzbuzz(n=100, mods={3:'Fizz', 5:'Buzz'}):
res = defaultdict(str)

for num, name in mods.items():
for i in range(num, n+1, num):
res[i] += name

return '\n'.join(res[i] or str(i) for i in range(1,n+1))
</lang>
</lang>