General FizzBuzz: Difference between revisions

Content added Content deleted
m (→‎{{header|Lua}}: Corrected mistake.)
(→‎{{header|Python}}: Changed last example to preserve order and duplicate moduli; changed variable names in previous example.)
Line 1,543: Line 1,543:


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


for i in range(1,n+1):
for i in range(1,n+1):
res = ''
res = ''
for k,v in cnts.items():
for mod, cnt in cnts.items():
v += 1
cnt += 1
if v == k:
if cnt == mod:
v = 0
cnt = 0
res += mods[k]
res += mods[mod]
cnts[k] = v
cnts[mod] = cnt
yield res or str(i)
yield res or str(i)


Line 1,562: Line 1,562:
</lang>
</lang>


'''Another version, using ranges with step 3, 5, etc.'''
'''Another version, using ranges with step 3, 5, etc. Preserves order and duplicate moduli.'''
<lang Python>from collections import defaultdict
<lang Python>from collections import defaultdict, OrderedDict


n = 100
def fizzbuzz(n=100, mods={3:'Fizz', 5:'Buzz'}):
mods = [
(3, 'Fizz'),
(5, 'Buzz'),
]

def fizzbuzz(n=n, mods=mods):
res = defaultdict(str)
res = defaultdict(str)


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


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


if __name__ == '__main__':
n = int(input())

mods = []
while len(mods) != -1: # for reading until EOF change 3 to -1
try:
line = input()
except EOFError:
break
idx = line.find(' ') # preserves whitespace
num, name = int(line[:idx]), line[idx+1:] # after the first space
mods.append((num, name)) # preserves order and duplicate moduli

print(fizzbuzz(n, mods))

</lang>
</lang>
{{Out}}
<pre>
>>> mods = [
... (2, 'Two '),
... (6, 'six '),
... (4, 'Four '),
... (6, 'HA! SIX!'),
... (8, 'eight... '),
... ]
>>> print(fizzbuzz(16, mods))
1
Two
3
Two Four
5
Two six HA! SIX!
7
Two Four eight...
9
Two
11
Two six Four HA! SIX!
13
Two
15
Two Four eight...
</pre>


=={{header|Racket}}==
=={{header|Racket}}==