python recursive function

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jan 11 03:53:51 EST 2008


Tom_chicollegeboy a écrit :
(snip)
> As you see my program must use recursion.

It's conceptually easier to express using recursions - but every 
recursion-based algorithm can be rewritten to use iteration (and 
vice-versa).

> I came up with this idea but I am not sure if its right or are there
> any minor errors that I can easily fix:
> 
> def bears (n):
>     if n==42:
>         return True
>     if n%5==0:
>         bears(n-42)

You want:
           return bears(n - 42)

>     if n%2==0:
>         bears(n/2)

idem

>     if n%3==0 or n%4==0:
>         one = (n%10)
>         two = ((n%100)/10)
>         if one!=0 and two!=0:
>             bears(n-(one*two))

idem

>     return False
> 



More information about the Python-list mailing list