Home > Software engineering >  Out of memory when use for loop to input parameter in recursive function Python
Out of memory when use for loop to input parameter in recursive function Python

Time:05-17

I have a recursive function:

def recursive_func(parameter1):
.....

I use for loop to input a parameter in recursive_func:

list_parameter_input = [a,b,c,d,e]
for item in list_parameter_input:
    recursive_func(i)

Note: my recursive_func is very complex but I'm sure it won't have any error.

The problem is when I input a parameter1 with a single item in list_parameter_input, it's fast and needs small memory. When I input a parameter1 using for loop, it's prolonged and makes out of memory.It's so weird.

I'm checked time when recursive_func complete with each value in list_parameter_input.

When input with not using for loop: recursive_func(a) need x time.

When input with using for loop: recursive_func(a) need more x time (10x,11x,...) but with b,c,d,e give a same time.

I don't know why it's happen but I'm really sure recursive_func(a) is very fast when I input a with not using for loop

CodePudding user response:

Maybe I misunderstand your description of the code (you are technically not providing a Minimal, Reproducible Example), but if the code looks like this:

def recursive_func(parameter1):

    ...

    list_parameter_input = [a,b,c,d,e]
    for item in list_parameter_input:
        recursive_func(item)

... then you have an infinite loop.

I.e. Unless the list_parameter_input is modified (items are removed) you are not making progress.

Can you verify that you are actually making progress through the input parameters?

CodePudding user response:

I mean recursive_func(i) is probably recursive_func(item) as you're never using i anywhere.

But the real problem seems to be that you're running the entire loop for each recursion. So each element of the list starts a recursion where it loops through the entire list, not just the rest of the list but the entire list. And each of the element of that loop does the same so:

5 recursions for the elements in the list

5*5 recursions for the elements in the list in the recursions

5*5*5 recursions for the elements in the list in the recursions of the recursion ...

That soon leads to a stack overflow.

  • Related