[Tutor] printing tree structure
karma
dorjetarap at googlemail.com
Fri Jul 3 15:21:37 CEST 2009
Thanks all for the feedback. As you all rightly pointed out, I was
confusing myself by not keeping a track of the recursion depth.
Thanks again
2009/7/3 Alan Gauld <alan.gauld at btinternet.com>:
>
> "karma" <dorjetarap at googlemail.com> wrote
>
>> thinking that a recursive solution would work here, but so far I can't
>> quite get it working. This is what I have so far:
>>
>> Can someone suggest whether this is suited to a recursive solution and
>
> Yes certainly
>
>> if so, what am I doing wrong.
>
>>>>> L = ['a',
>
> ['b', ['d', [], [] ],
> ['e', [], [] ]
> ], ['c',
> ['f', [], [] ], []
> ]
> ]
>
>>>>> def printTree(L):
>>
>> for i in L:
>> if isinstance(i,str):
>> print 'Root: ', i
>> else:
>> print '--Subtree: ', i
>> printTree(i)
>>
>
>>>>> printTree(L)
>>
>> Root: a
>> --Subtree: ['b', ['d', [], []], ['e', [], []]]
>> Root: b
>> --Subtree: ['d', [], []]
>> Root: d
>> --Subtree: []
>> --Subtree: []
>
> This is the end of the recursive call to printTree( ['d', [ [], [] ] ]
>
>> --Subtree: ['e', [], []] # this shouldn't be here
>
> This is the next element in printTree( ['d', [], []], ['e', [], []] )
>
>> Root: e
>
> This is the start of printTree( ['e', [], [] ] )
>
>> --Subtree: []
>> --Subtree: []
>
> Now why do you think the line you highlighted is an error?
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list