Jump to content

General FizzBuzz: Difference between revisions

→‎{{header|Python}}: Modified second example to use a generator; added another example.
m (→‎{{header|Python}}: Corrected mistake.)
(→‎{{header|Python}}: Modified second example to use a generator; added another example.)
Line 1,483:
 
 
'''Alternative version - generator using counters instead of modulo'''
{{works with|Python|3.x}}
<lang Python>n = 100
Line 1,492:
 
def fizzbuzz(n=n, mods=mods):
res = ''
cnts = {k:0 for k in mods.keys()}
 
for i in range(1,n+1):
wrres = False''
for k,v in cnts.items():
v += 1
Line 1,502 ⟶ 1,501:
v = 0
res += mods[k]
wr = True
cnts[k] = v
yield res +=or str(i)
 
if not wr:
res += str(i)
res += '\n'
 
return res
 
 
if __name__ == '__main__':
n = int(input())
mods = { int(k): v for k,v in (input().split(maxsplit=1) for _ in range(3)) }
print(for line in fizzbuzz(n, mods)):
if not wr: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] wr += Truename
 
return '\n'.join(res[i] or str(i) for i in range(1,n+1))
</lang>
 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.