-
-
Save reikoNeko/b30d671f6f167ec06086d6208e5b2e93 to your computer and use it in GitHub Desktop.
def fizzbuzz(n): | |
for x in range(1,n+1): | |
result='' | |
if not x%3: result += ('fizz') | |
if not x%5: result += ('buzz') | |
yield result if result else str(x) |
And here's a more pythonic version
def fizzbuzz(n):
for x in range(1,n+1):
result=''.join([a*b for a,b in zip(('fizz','buzz'), (not x%3, not x%5))])
yield result if result else str(x)
Got challenged to do it with out modulus or division. Yay itertools.
from itertools import cycle
fizz='001'
buzz='00001'
def fizzbuzz(n):
for v,f,b in zip(range(1,n+1), cycle(fizz), cycle(buzz)):
fb = ('fizz' if int(f) else '') + ('buzz' if int(b) else '')
yield fb if fb else v
This all grew out of a thread on the mailing list for the Philadelphia Linux User Group about https://blog.codinghorror.com/why-cant-programmers-program
And this was before I read https://blog.codinghorror.com/fizzbuzz-the-programmers-stairway-to-heaven/
The whole point of the original article was to think about why we have to ask people to write FizzBuzz. The mechanical part of writing and solving FizzBuzz, however cleverly, is irrelevant. Any programmer who cares enough to read programming blogs is already far beyond such a simple problem. FizzBuzz isn't meant for us. It's the ones we can't reach – the programmers who don't read anything – that we're forced to give the FizzBuzz test to.
C'est la vim.
Your last iteration of FizzBuzz was actually something worth checking out. Excellent use of a generator in a unique and compact manner. Not sure if you want to go to production with that code but you go girl!
In production I'd cheat more and also consider memoization. :)
print(*[x for x in fizzbuzz(30)])
1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz