python recursive function

Nick Craig-Wood nick at craig-wood.com
Fri Jan 11 13:30:04 CET 2008


HYRY <ruoyu0088 at gmail.com> wrote:
>  def bears (n):
>      if n==42:
>          return True
>      if n%5==0:
>          if bears(n-42):
>              return True
>      if n%2==0:
>          if bears(n/2):
>              return True
>      if n%3==0 or n%4==0:
>          one = (n%10)
>          two = ((n%100)/10)
>          if one!=0 and two!=0:
>              if bears(n-(one*two)):
>                  return True
>      return False

Almost but you missed a case...

>>> for i in range(100):
...     try:
...         print i, bears(i)
...     except RuntimeError, e:
...         print i, e
...
0 0 maximum recursion depth exceeded
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 10 maximum recursion depth exceeded
11 False
12 12 maximum recursion depth exceeded
113 False
14 False
15 15 maximum recursion depth exceeded
16 16 maximum recursion depth exceeded
17 False
[snip]
89 False
90 90 maximum recursion depth exceeded
91 False
92 False
93 93 maximum recursion depth exceeded
94 False
95 False
96 96 maximum recursion depth exceeded
97 False
98 False
99 99 maximum recursion depth exceeded

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list