Anonymous user
General FizzBuzz: Difference between revisions
→{{header|Python}}: Changed last example to preserve order and duplicate moduli; changed variable names in previous example.
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:
def fizzbuzz(n=n, mods=mods):
cnts = {
for i in range(1,n+1):
res = ''
for
if
res += mods[
cnts[
yield res or str(i)
Line 1,562:
</lang>
'''Another version, using ranges with step 3, 5, etc. Preserves order and duplicate moduli.'''
<lang Python>from collections import defaultdict, OrderedDict
n = 100
def fizzbuzz(n=100, mods={3:'Fizz', 5:'Buzz'}):▼
mods = [
(3, 'Fizz'),
(5, 'Buzz'),
]
res = defaultdict(str)
for num, name in mods
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))
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>
{{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}}==
|