Ad

How To Store Values Globally In Recursive Calls In Python

I have a doubt regarding backtracking appraoch in python . How do i store the variables and list (temporary) so formed in different calls in recursion in python as we know as soon as the power stacks formed gets destroyed , the variable's value also gets destroyed . for ex :

avc=[]
var=0
def func(li,n,sumo,li2):
if sumo==n:
    global var
    var+=1
    #print(li2) ##line x
    adg(li2)
    return 
elif sumo>n:
    return 
else:
    for i in range(0,len(li)):
        li2.append(li[i])
        sumo=sum(li2)
        func(li,n,sumo,li2)
        li2.remove(li[i])

def adg(li3):
   global avc 
   avc.append(li3)
   #print("avc",avc)



if __name__=="__main__" :
   liq=list(map(int,input().strip().split()))
   n=liq[0]
   li=list(map(int,input().strip().split()))
   func(li,n,0,[])
   sumo=0
   count=0
   lis=[]
   j=0
   print(avc)

Now at line x it do prints the list but when i print the avc at the end of program, it prints the empty list. i want elements to get appended to avc . please help.

Ad

Answer

You should change

   avc.append(li3)

to

   avc.append(li3.copy())

That is because avc holds a reference to li3, and by doing

 li2.remove(li[i])

You remove items from li3 also, because you passed li2 to adg where it's called li3.

By calling .copy() on li3 you get a new list with the same elements, so when you change li2 (or li3) the copied list doesn't get changed.

Ad
source: stackoverflow.com
Ad