Search code examples
pythondictionaryrecursionlocal

Make dictionary act as local variable for recursive function


I have a recursive function with a dictionary as an argument, the function changes the dictionary before it calls itself. I would like the change of the dictionary to only affect the called function and nothing outside the of the scope.

Can I create a local dictionary?

dict = {10 : 5, 20 : 5}

def recursive_func(dict_arg, total_arg):
    dict_local = dict_arg

    for k, v in dict_local.items():
        total = total_arg + k
        if total >= 25:
            dict_local.update({k : v -1})
            print(str(total) + str(dict_local))
        else:
            dict_local.update({k : v -1})
            recursive_func(dict_local, total)

print("dict before func: " + str(dict))
recursive_func(dict, 0)
print("dict after func: " + str(dict))


terminal >>>
dict before func: {10: 5, 20: 5}
30{10: 2, 20: 5}
40{10: 2, 20: 4}
30{10: 2, 20: 3}
30{10: 1, 20: 2}
40{10: 1, 20: 1}
dict after func: {10: 1, 20: 1}

As can be seen the dictionary is changed after the function and the printed total does not match with the coresponding amount of 10 and 20's left in the dictionary.


Solution

  • dict = {10 : 5, 20 : 5}
    
    def recursive_func(dict_arg, total_arg):
    
        for k, v in dict_arg.items():
            dict_local = dict_arg.copy()
            total = total_arg + k
            if total >= 25:
                dict_local.update({k : v -1})
                print(str(total) + str(dict_local))
            else:
                dict_local.update({k : v -1})
                recursive_func(dict_local, total)
    
    print("dict before func: ", str(dict))
    recursive_func(dict, 0)
    print("dict after func: ", str(dict))
    
    
    >>>
    dict before func:  {10: 5, 20: 5}
    30{10: 2, 20: 5}
    40{10: 3, 20: 4}
    30{10: 4, 20: 4}
    30{10: 4, 20: 4}
    40{10: 5, 20: 3}
    dict after func:  {10: 5, 20: 5}