Alexander Ameye
Alexander Ameye

Reputation: 185

'Remembering' a variable when using a recursive algorithm?

I have this code:

def function(pos):
    new_list = []

    if condition:
        for x in range(0,len(another_list)):
            new_pos = another_list[x]
            new_list.append(new_pos)
            function(new_pos)

where another_list is a list that is defined elsewhere, and I can access it.

When the given position meets a certain condition, I'm looping through another_list and I'm adding positions, but of course everytime I call function, new_list gets reset and all the values in it are removed.

I want to have new_list contain all the new_pos values and not get reset each time function gets called, and I only want it to be cleared when I tell it to. How should I achieve this?

Upvotes: 0

Views: 2148

Answers (4)

Jared Goguen
Jared Goguen

Reputation: 9010

If you're trying to accumulate the result of each function call, you could change the last line of your function to:

return new_list + function(new_pos)

Then, you'll also want to add a return new_list in the case where condition is not satisfied.

A generic recursive function of this nature might look like:

def generic_function(param):

    # break recursion when condition is not met
    if not condition:
        return []

    else:
        temporary_list = []
        # do stuff
        return temporary_list + generic_function(new_param)

This might be a better approach than trying to "remember" an object down through the recursion. If it turns out that is truly necessary, see martineau's answer which addresses that problem.

Upvotes: 0

Roll
Roll

Reputation: 299

I thought this might help you.

def function(first_pos):

    def foo(pos):
        if condition:
            for x in range(0, len(another_list)):
                new_pos = another_list[x]
                new_list.append(new_pos)
                foo(new_pos)

    new_list = []
    foo(first_pos)
    return new_list

Upvotes: 0

martineau
martineau

Reputation: 123473

This is typically done by adding an argument to the function to hold the "remembered" value and giving it a default value so it doesn't have to be provided to the upper-most level call. The function can return this value as shown if it's that type of function (as opposed to one that is executed only for its side-effects).

def function(pos, new_list=None):
    if new_list is None:
        new_list = []

    if condition:
        for x in range(0,len(another_list)):
            new_pos = another_list[x]
            new_list.append(new_pos)
            function(new_pos, new_list)

    return new_list

# same usage
pos = 42
result_list = function(pos)

Upvotes: 2

Faceplanted
Faceplanted

Reputation: 71

new_list=[] needs to be an argument with a default value in your function, so you pass it through to the next call, but when you call it the first time it defaults to an empty list

Upvotes: -1

Related Questions