user1684046 user1684046 - 29 days ago 7
Python Question

How to eliminate recursion in Python function containing control flow

I have a function of the form:

def my_func(my_list):
for i, thing in enumerate(my_list):
my_val = another_func(thing)

if i == 0:
# do some stuff
else:
if my_val == something:
return my_func(my_list[:-1])
# do some other stuff


The recursive part is getting called enough that I am getting a RecursionError, so I am trying to replace it with a while loop as explained here, but I can't work out how to reconcile this with the control flow statements in the function. Any help would be gratefully received!

Answer
def my_func(my_list):
    run = True
    while run:
        for i, thing in enumerate(my_list):
            my_val = another_func(thing)

            if i == 0:
                # do some stuff
            else:
                if my_val == something:
                    my_list = my_list[:-1]
                    break
                # do some other stuff    

This is an iterative method.

Comments