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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad