Responsive Ad Area

Share This Post

test

Why are my python variables acting globally during recursion?

I have a recursive function that doesn’t work the way I want it to. Inside the function, I have a variable called sum. I want the variable to be local / a different one for each function call, so that the final sum becomes the sum of all earlier function calls. However, it seems like the variable is acting globally, so every time the function is called, the sum variable is set to 0, and that is what is returned in the end. I have the same problem with the list: for each function call, an element is removed from my_list in all the different recursion frames, rather than just the local frame as I want it to. Is this how variables are supposed to work during recursion in python? If it is, how can I change the code to make it work the way I want it to?

By the way, the purpose of the function is to find out if there exists a subset of a list that adds up to the number n, but this is not very relevant for understanding the issue I have.

I have searched for similar posts, and I found someone arguing that you’re not invoking a recursion unless you use the return statement to return the function like this:

return f(n – x, remove(list, x))

However, if that is the case, I don’t see how I can both return the function and add the value to the sum at the same time.

list1 = [3, 5, 1, 2, 5, 3, 4]

# removes an element from the list, and returns the result
def remove(list_, x):
    list_.remove(x)
    return list_

# recursive function
# should return 1 or more if there exists a combination of numbers in the list
# that add up to the number n
def f(n, my_list):
    sum = 0

    if n == 0:
        return 1
    if len(my_list) == 0:
        return 0
    for x in list:
        sum += f(n - x, remove(my_list, x))

    return sum


print(f(15, list1))

There exists a subset of the list that adds up to 15: for example (5, 1, 5, 4), so the output should be at least 1, but because of the fact that the variables are acting globally, the output is always 0.


Why are my python variables acting globally during recursion?
Why are my python variables acting globally during recursion?
test
{$excerpt:n}

Share This Post

Leave a Reply

Your email address will not be Publishedd. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Skip to toolbar