Recursive calls and stack
Szabolcs Nagy
nszabolcs at gmail.com
Wed Feb 14 22:04:31 EST 2007
jm.suresh at no.spam.gmail.com wrote:
> Hi,
> I have a program which literately finds the object that overlapping a
> point. The horizontal and vertical search are called recursively from
> inside each other.
> ...
in case you ever need deeply nested recursion:
one solution is to use the already mentioned sys.setrecursionlimit(n)
another is to use your own stack
dummy example:
def fact_recursive(n):
if n>0:
return fact_recursive(n-1)*n
else:
return 1
def fact_iterative(n):
stack = []
while n > 0:
stack.append(n)
n -= 1
ret = 1
while stack:
ret *= stack.pop()
return ret
actually you can always rewrite recursion with a stack and iterations
note that if you use version >= 2.4, then collections.deque is faster
for stack (and especially for queue) data structure than list.
More information about the Python-list
mailing list