Fun transformation problem
Jonathan Wright
quaggy at gmail.com
Thu Aug 26 21:25:45 EDT 2004
def trans(paths):
tree = {}
for path in paths:
branch = tree
for i,node in enumerate(path[:-2]):
branch = branch.setdefault(node, {})
branch[path[-2]] = path[-1]
return tree
print trans( [(1,2,3), (1,3,4), (2,5,6)] )
print trans( [(1,2,3,4), (3,4,5,6), (3,4,6,7), (3,4,6,8), (3,4,5,1),
(3,4,7,9)] )
This is my first post with gmail. The preview shows it screwing up the
spaces in the python code, so I'm includeding a version with dots
instead of spaces below. :-)
def trans(paths):
....tree = {}
....for path in paths:
........branch = tree
........for i,node in enumerate(path[:-2]):
............branch = branch.setdefault(node, {})
........branch[path[-2]] = path[-1]
....return tree
Jonathan.
More information about the Python-list
mailing list