Add tags

Add tags to the following comment

Pythonだとこんな感じでしょうか。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Node:
    def __init__(self, name):
        self.name = name
        self.parent = None
        self.children = []

def pairs_to_trees(pairs):
    nodes = {}
    for parent_name, child_name in pairs:
        parent = nodes.setdefault(parent_name, Node(parent_name))
        child  = nodes.setdefault(child_name,  Node(child_name))
        child.parent = parent
        parent.children.append(child)
    return [node for node in nodes.itervalues() if node.parent is None]

def show(node, depth):
    if depth == 0:
        print node.name
    else:
        print "  " * (depth - 1) + "->" + node.name
    for child in node.children:
        show(child, depth + 1)

def main():
    pairs = [
        ('A', 'B'),
        ('B', 'C'),
        ('C', 'D'),
        ('C', 'E'),
        ('A', 'F'),
        ('D', 'X'),
        ('Y', 'Z'),
        ('Z', 'C'),
    ]

    for tree in pairs_to_trees(pairs):
        show(tree, 0)

if __name__ == '__main__':
    main()

Add tags

The input will be splited to tags with space.

Index

Feed

Other

Link

Pathtraq

loading...