Using the code below, a user is facing an issue that it always returns an empty list. If he bring root nodes out of the function, Python complains that the local variable root nodes is referenced before it is instantiated.

781    Asked by NikitaGavde in Data Science , Asked on Nov 17, 2019
Answered by Nikita Gavde

def findrootnodes(tree):

    rootnodes = []

    if tree.results != None:

        root nodes += tree.results

    else:

        findrootnodes(tree.tb)

        findrootnodes(tree.fb)

    return root nodes

In the findroot nodes function, the value of root nodes for non-result nodes is never changed. That is, when we call findrootnodes, we first set:

rootnodes = []

And then we run

findrootnodes(tree.tb)

findrootnodes(tree.fb)

which return an empty list.

The following code can solve the problem

def findrootnodes(tree):

    rootnodes = []

    if tree.results != None:

        rootnodes.append(tree.results)

    else:

        rootnodes.extend(findrootnodes(tree.tb))

        rootnodes.extend(findrootnodes(tree.fb))

    return root nodes

Here the += is changed to append function because Trying to add a dictionary to a list via += will treat the dictionary as an iterable, which Python will iterate over just the keys.


Your Answer

Interviews

Parent Categories