Ado Riadh Ado Riadh - 13 days ago 5
Python Question

Recursive call blocked

def getCategoriesAsList(element):
try:
print "I am {0}".format(element.getNodeID())
if element.hasChilds():
for value in element.getChildren().values():
print "{0} added to list".format(value.getNodeID())
return [value]+getCategoriesAsList(value)
else:
print "{0} added to list".format(element.getNodeID())
return [element]
except Exception as err:
print err


Good morning!
I am trying to iterate over my tree in python and i want to transform the tree into a list of element with some transformations.
The problem is the function does not perform a recursive call when the element has not child. I make some debug information but i can not understand this behavior!

Answer

If it's possible to change the function notation a bit, you might as well pass a result list as an argument that collects values along the way:

def getCategoriesAsList(element, result):
    try:
        print "I am {0}".format(element.getNodeID())
        if element.hasChilds():
            for value in element.getChildren().values():
                print "{0} added to list".format(value.getNodeID())
                result.append(value)
                getCategoriesAsList(value, result)
        else:
            print "{0} added to list".format(element.getNodeID())
            result.append(element)
    except Exception as err:
        print err

And than use the function like that:

result = []
getCategoriesAsList(root, result)
print result

One more thing to mention here. I should warn you that with your approach the value of the root might be missed in a result list.

Comments