Best Answer · By JanBask Data Science Expert
Answered on Nov 17, 2019
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.