I am not understanding the following code (I did not write it). It demonstrates walking a tree-like data structure using recursion. It does run and produces reasonable output. I particularly do not understand the "traverse.level" statements. Can anyone give me an idea how this is working and the principles? I would like understand recursive calls in Python better as I have not used the technique previously.
Thanks, Bill 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': []}]}, {'count': 0, 'text': '1.1.2', 'kids': [{'count':0, 'text': '1.1.1.2', 'kids': [{'count':0, 'text': '1.1.1.1.1', 'kids': []}]}]}, {'count': 0, 'text': '1.1.3', 'kids': []}]}, {'count': 0, 'text': '1.2', 'kids': []}]} 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)
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor