I passed a fizzbuzz test but failed at recursion.

Michael Rudolf spamfresser at ch3ka.de
Sun Mar 14 12:25:35 CET 2010


Am 10.03.2010 16:55, schrieb Bill:
> def fizzbuzz(num):
>      if num:
>          if num % 15 is 0: return fizzbuzz(num-1) + 'fizzbuzz \n'
>          elif num % 5 is 0: return fizzbuzz(num-1) + 'buzz \n'
>          elif num % 3 is 0: return fizzbuzz(num-1) + 'fizz \n'
>          else : return fizzbuzz(num-1) + ('%d \n' % num)
>      return ''
> print fizzbuzz(100)

While I do understand that this is not a Perl group, and this probably 
won't help the OP, I just could not resist:

for i in range(1,101):print('','fizz')[not i%3]+('','buzz')[not i%5]or i

 > However, when I try to decipher the logic of the function I imagine
 > the solution reversed as "buzz fizz 98 97 ...etc... 4 fizz 2 1".

No, the function creates the string from right to left.
See:
fizzbuzz(100) = fizzbuzz(99) + "buzz \n"
= fizzbuzz(98) + "fizz \n" + "buzz \n"

...

= fizzbuzz(1) + "2 \n" + "fizz \n" + "4 \n" + "buzz\n " + "fizz \n" + 
.... + "97 \n" + "98 \n" + "fizz \n" + "buzz \n"

= fizzbuzz(0) + "1 \n" + "2 \n" + "fizz \n" + "4 \n" + "buzz\n " + "fizz 
\n" + .... + "97 \n" + "98 \n" + "fizz \n" + "buzz \n"

= " " + "1 \n" + "2 \n" + "fizz \n" + "4 \n" + "buzz\n " + "fizz \n" + 
.... + "97 \n" + "98 \n" + "fizz \n" + "buzz \n"

Regards,
Michael



More information about the Python-list mailing list