Nested recursive function in python -
i tried implement nested recursive function in python giving error "runtimeerror: maximum recursion depth exceeded" can see function in following code. regarding question appreciated.
n=10 def test(n): if n<=0: return 1 else: return test(test(n-1)+1) print test(n)
one important part of recursion every recursive call have closer anchor case, in case is:
if n<=0: return 1
however, code not getting close case. problem line:
return test(test(n-1)+1)
since test returns 1
when reaches end case , add 1 result, let's see happens when call test(2)
:
the anchor case isn't executed , go straight else
. return
test(test(1)+1)
since 2-1=1
. inner test call going go else
case , call:
test(test(0)+1)
here inner test call returns 1 (it has reached end case) means in line calling
test(2) //test(1+1)
again. here can see recursion never ending, hence maximum recursion depth exceeded error
.
just clarify how make code (which example) work:
def test(n): if n <= 0: return 1 else: return test(test(n-1)-1) //notice -1 instead of +1
follow question:
why changing recursive call test(test(n-2)) result in infinite recursion?
well because of same reason pointed out right @ beginning. need closer anchor case. while can reach case of n<=0
inside nested recursive call test(n-2)
can not reach inside outer function call.
note function returns 1 when reaches it's end case, if test(n-2)
doesn't cause more recursions returns 1 (not 0), means end with
test(1)
which again going cause infinite loop (since can not n <= 0
outer function call).
you have multiple options make recursion work case: changing return value or changing anchor case. changing if statement either of these prevent infinite recursion:
if n <= 0: return 0
or
if n <= 1: return 1 //you return other value <= 1
Comments
Post a Comment