Python recursion not returning value
For some reason x in this code is not updating within the recursion. Shouldn't x update as I'm calling b(c) within a(y)? When x updates in b(c) but doesn't return to
global nested
def extract(nested,depth):
y = depth[0]
depth = depth[1:]
extract = nested[y]
newlist(extract)
return depth
def newlist(x):
nested = x
return nested
def recursiveRef(nes开发者_开发百科ted,depth):
"""Return element from nested list
list ->int
"""
if len(depth) == 0:
return nested
else:
return recursiveRef(nested,extract(nested,depth))
Is this what you are trying to do?
def recursiveRef(nested,depth):
"""Return element from nested list
list ->int
"""
if len(depth) == 0:
return nested
else:
return recursiveRef(nested[depth[0]],depth[1:])
print recursiveRef([[1,2,3],[4,[5,6],7]],[1])
print recursiveRef([[1,2,3],[4,[5,6],7]],[1,1])
print recursiveRef([[1,2,3],[4,[5,6],7]],[1,1,1])
Output
[4, [5, 6], 7]
[5, 6]
6
I am not a Python
master but I think the problem is that x
is local to the recursion function. You are changing an other global x
in your b(c)
. Please, correct me if I am wrong.
Your code looks suspicious. When you think you want a global variable, usually you want a class. Consider wrapping your functions in a class and use self.x instead of x.
That said, "global" should not be written in the top of your program. Instead, you need it in every function that modifies your global variable, but not those that only reads it.
def newlist(x):
global nested
nested = x
return nested
The x
variable in the b
function is not binded to the one in the recursion
function.
I really don't understand what you are tring to do -- I can be wrong but I suggest you to consider to put the two functions a
and b
into recursion
, creating a closure.
In that way the nested functions can see and modify all the variables defined in the outer scope.
An even simpler non-recursive version:
def inTree(tree, ref):
for offs in ref:
tree = tree[offs]
return tree
精彩评论