[Tutor] not understanding a recursion example

Bill Allen wallenpb at gmail.com
Fri Jan 21 06:56:19 CET 2011


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)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110120/c3350f37/attachment.html>


More information about the Tutor mailing list