Python recursion does not return value

For some reason, x in this code is not updated in recursion. Should I not update x when I call b (c) within (y)? When x is updated in b (c) but does not 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(nested,depth):
    """Return element from nested list
    list ->int
    """
    if len(depth) == 0:
        return nested
    else:
        return recursiveRef(nested,extract(nested,depth))
+3
source share
5 answers

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
+3
source

I am not a master Python, but I think the problem is what xis local to the recursion function. You change another global xin yours b(c). Please correct me if I am wrong.

+1
source

. , , . self.x x.

, "" . , , , .

def newlist(x):
    global nested
    nested = x
    return nested
+1

A variable xin a function is bnot bound to function c recursion.

I really don’t understand what you are doing - I could be wrong, but I suggest you consider turning on two functions aand bin recursion, creating a closure. In this way, nested functions can see and change all the variables defined in the outer scope.

0
source

An even simpler non-recursive version:

def inTree(tree, ref):
    for offs in ref:
        tree = tree[offs]
    return tree
0
source

All Articles