java - How do I create a tree out of this? -
i have text file has content this:
a.b.c.d a.c a.d a.x.y.z a.x.y.a a.x.y.b a.subtree i want make tree:
/ / \ \ \ b c d x subtree | | c y | / | \ d z b edit: a.x.y.a path 2 a nodes need treated seperate entities. a.x.y.a path.
we can @ input file this:
level0.level1.level2... i'm trying in python (i'm familiar java too, java answers well) somehow i'm logically not able it.
my basic tree structure kind of this:
class tree: def __init__(self,data): self.x = data self.children = [] logic this:
for line in open("file","r"): foos = line.split(".") foo in foos: put_foo_in_tree_where_it_belongs() how approach this?
also, if there java library helping me this, can shift java well. need accomplish this.
the basic algorithm should this:
def add_path(root, path): if path: child = root.setdefault(path[0], {}) add_path(child, path[1:]) root = {} open('tree.txt') f: p in f: add_path(root, p.strip().split('.')) import json print json.dumps(root, indent=4) output:
{ "a": { "x": { "y": { "a": {}, "z": {}, "b": {} } }, "c": {}, "b": { "c": { "d": {} } }, "d": {}, "subtree": {} } }
Comments
Post a Comment