Solving the problem of mutual recursion

Peter Brooks peter.h.m.brooks at gmail.com
Sun May 26 07:49:57 EDT 2013


I'm not sure if this'll interest anybody, but I expect that I'm going
to get some mutual recursion in my simulation, so I needed to see how
python handled it. Unfortunately, it falls over once it detects a
certain level of recursion. This is reasonable as, otherwise, the
stack eventually over-fills.

Mostly the recommendation, when this happens, is to re-write the code
as loops. Of course, that's not as satisfactory as using recursion.

The problem really is that the methods or functions called recursively
never exit because they're waiting for the return of the function
they've called. Now, if your recursion relies upon knowing what's
returned, then this solution won't help you. Often, though, you're not
interested in what's returned and would just like the routine to exit
once it's called itself, or another process, recursively.

If that's the case, this solution, using threads, allows you to have
functions call themselves, or each other, indefinitely. It works OK on
a macbook pro and the thread count varies from 2-3, so it handles the
thread queuing well. I'm not sure how well this will work on other
architecture - it'd be interesting to know if anybody tries it.

#!/usr/bin/python
# Two functions, Jim and Fred, call each other recursively and
indefinitely, while the main program continues to execute as well
import threading, time

def jim(arg,count):
        print "Running jim:", arg,count," Thread Count
",threading.active_count()
        thread = threading.Thread(target=fred, args=(" From Jim ",count
+1))
        thread.start()
        print count," Jim complete. Thread
Count",threading.active_count()

def fred(arg,counter):
        print "Running fred:", arg,counter
        thread = threading.Thread(target=jim, args=(" From Fred
",counter+1))
        thread.start()
        print counter,"Fred complete",threading.currentThread()


thread = threading.Thread(target=jim, args=(" From Main",0))
thread.start()
print "Jim run from main"
count = 0
while True:
        count += 1
        print 'In main program',count



More information about the Python-list mailing list