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 = { |
cnts = {mod:0 for mod in mods} |
||
for i in range(1,n+1): |
for i in range(1,n+1): |
||
res = '' |
res = '' |
||
for |
for mod, cnt in cnts.items(): |
||
cnt += 1 |
|||
if |
if cnt == mod: |
||
cnt = 0 |
|||
res += mods[ |
res += mods[mod] |
||
cnts[ |
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 |
|||
⚫ | |||
mods = [ |
|||
(3, 'Fizz'), |
|||
(5, 'Buzz'), |
|||
] |
|||
⚫ | |||
res = defaultdict(str) |
res = defaultdict(str) |
||
for num, name in mods |
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}}== |