Question

I am using a recursive function call to traverse a tree and I want to add the locations of valuable nodes to a master list. My current method is to use a global. How do I pass this list by reference instead (or solve this in another way without globals)

hcList = []

def expand(node):
    global hcList

    if node.hasTreasure():
        hcList.append(node)
    if not node.end():
        expand(node.next())

global hcList
expand(startnode)
hcList.filter()

Anyway to do something like below without using a hairy global? My actual code is much messier with globals but the concepts are the same. The code below doesn't work the way I want it to. Namely, hcList is empty.

def expand(node, hcList):      
    if node.hasTreasure():
        hcList.append(node)
    if not node.end():
        expand(node.next(), hcList)

hcList = []
expand(startnode, hcList)
hcList.filter()
Was it helpful?

Solution

For recursion, it is frequently simpler to return the new value

def expand(node, hcList):
    if node.hasTreasure:
         hcList.append(node)
    if node.end():
         return hcList
    return expand(node.next(), hcList)

hcList = expand(startnode, [])
hcList.filter() # not sure why this was in the OP

If your list is very deep, you may have a lot on the stack, but good tail recursion can optimize that away.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top