I'm working with a recursive function to add all the integers in nested lists.
def myFunction(L):
K=[]
for eachItem in L:
if isinstance(eachItem, list):
myFunction(eachItem) #to deal with nested Lists.
else:
K.append(eachItem)
return sum(K) #add em up!
print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))
Result: 9
This fails because K=[] is inside a recursive function, so only the totally unnested values are summed.
I can fix it by doing this:
K=[] #moved it up here
def myFunction(L):
for eachItem in L:
if isinstance(eachItem, list):
myFunction(eachItem) #to deal with nested Lists.
else:
K.append(eachItem)
return sum(K) #add em up!
print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))
Now I get the result that I want, 12.
But when I try to do the same thing with an integer:
def myFunction(L):
K=0
for eachItem in L:
if isinstance(eachItem, list):
myFunction(eachItem) #to deal with nested Lists.
else:
K +=eachItem
return K #add em up!
print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))
Having K inside the loop is giving an incorrect answer, i.e., 9, and moving it out:
K=0
def myFunction(L):
for eachItem in L:
if isinstance(eachItem, list):
myFunction(eachItem) #to deal with nested Lists.
else:
K +=eachItem
return K #add em up!
print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))
It gives me this error "UnboundLocalError: local variable 'K' referenced before assignment" because it can't do "K +=eachItem" so, K isn't a part of the variable in the function?
Why do one work-around work and the other fail? I want to "declare variables" but this is not a python thing. Should I look in to "global variables"?