tree data structure

Raymond Hettinger python at rcn.com
Fri Sep 6 08:15:54 EDT 2002


There are a number of ways to represent trees:
-- instances of a treenode class
-- a list of lists:  [l0, [s2, [s0, [q1]], [s1,[q2]], [s3]]]
-- or, my favorite, a dictionary of lists:

>>> original = [('L0','S2'), ('S2','S0'), ('S2','S1'),
     ('S1','Q2'), ('S0','Q1'), ('S2','S3')]
>>> tree = {}
>>> for key, value in original:
 tree.setdefault(key,[]).append(value)

>>> tree
{'S2': ['S0', 'S1', 'S3'], 'S1': ['Q2'], 'S0': ['Q1'], 'L0': ['S2']}



Raymond Hettinger



"Padraig Brady" <Padraig at Linux.ie> wrote in message
news:FM0e9.2860$cP3.6165 at news.iol.ie...
> Hi,
>
> I've a graph like stucture represented
> by a list of tuples:
>
> [(L0,S2), (S2,S0), (S2,S1), (S1,Q2), (S0,Q1), (S2,S3)]
>
> And would like to convert it to
> a tree structure like:
>
>            S0 - Q1
>          /
> L0 - S2 - S3
>          \
>            S1 - Q2
>
> Any tips appreciated.
>
> Thanks,
> Pádraig.
>





More information about the Python-list mailing list