I passed a fizzbuzz test but failed at recursion.

Chris Hulan chris.hulan at gmail.com
Wed Mar 10 11:24:00 EST 2010


On Mar 10, 10:55 am, Bill <bsag... at gmail.com> wrote:
> Look at this recursive fizzbuzz function fromhttp://www.codinghorror.com/blog/2007/02/why-cant-programmers-program...
>
> 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)
>
> This returns "1 2 fizz 4 ...etc... 97 98 fizz buzz" which is correct.
>
> 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".
>
> After all, the first num is 100 which decrements by one until a zero
> stops the recursive loop.
>
> My (faulty) reasoning is that fizzbuzz(100) would firstly print a
> "fizz" and  the last fizzbuzz(1) would finally print a "1".
>
> My logic is wrong, but I don't know why.

There's only one print, it prints the string returned by fizzbuzz(100)
The string is constructed via recursion
ie:
fizzbuzz(6)
 fizzbuzz(5)
  fizzbuzz(4)
   fizzbuzz(3)
    fizzbuzz(2)
     fizzbuzz(1)
      fizzbuzz(0)
     ''+'1 \n'
    '1 \n'+'2 \n'
   '1 \n2 \n'+'fizz \n'
  '1 \n2 \n fizz \n'+'4 \n'
 '1 \n2 \n fizz \n4 \n'+'buzz \n'
'1 \n2 \n fizz \n4 \nbuzz \n'+'fizz \n'

print '1 \n2 \n fizz \n4 \nbuzz \nfizz \n'

clear as mud ;)



More information about the Python-list mailing list