In Python recursion example to navigate tree data, Sofeng presents this solution…
def outer(data): class Namespace: pass ns = Namespace() ns.level = 1 def inner(data): print ' ' * ns.level + data['text'] if data['count'] > 0: ns.level += 1 for kid in data['kids']: inner(kid) ns.level -= 1 inner(data) if __name__ == '__main__': outer(data)
…for traversing a dictionary of the form:
data = {'count': 2, 'text': '1', 'kids': [{'count': 3, 'text': '1.1', 'kids': [{'count': 1, 'text': '1.1.1', 'kids': [{'count':0, 'text': '1.1.1.1', 'kids': []}]}, ... }
Since his blog doesn’t seem to support code formatting in the comments, I’m repeating my comment here:
You actually don’t need the ‘count’ keys in the data dictionary, nor do you need the “if data['count'] > 0:” block. The code can be simplified even further by using a closure instead of the ‘Namespace’ class, eliminating the need for two (“outer” & “inner”) routines:
def traverse(data):
print ' ' * traverse.level + data['text']
for kid in data['kids']:
traverse.level += 1
traverse(kid)
traverse.level -= 1
if __name__ == '__main__':
traverse.level = 1
traverse(data)
Recent Comments