Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $> cat input.txt
- {'d2': [{'childs': [{'childs': [{'childs': None, 'name': 'X'}], 'name': 'C'}], 'name': 'B'}], 'd1': [{'childs': [{'childs': [{'childs': [{'childs': None, 'name': 'D'}], 'name': 'C'}], 'name': 'B'}], 'name': 'A'}, {'childs': None, 'name': 'E'}]}
- $>vi test1.py
- class Node(object):
- def __init__(self, name):
- self.name = name
- self.children = []
- def add_child(self, child):
- self.children.append(child)
- def flatten_to_dict(self):
- my_dict = {'name': self.name, 'childs': []}
- for child in self.children:
- my_dict['childs'].append(child.flatten_to_dict())
- return my_dict
- @staticmethod
- def from_dict(inp_dict):
- root = Node(inp_dict['name'])
- if not inp_dict['childs']:
- return root
- for child in inp_dict['childs']:
- root.add_child(Node.from_dict(child))
- return root
- def __repr__(self):
- return "%s" % self.flatten_to_dict()
- def find_node_with_name(self, name):
- if self.name == name:
- return self
- for child in self.children:
- found_node = child.find_node_with_name(name)
- if found_node:
- return found_node
- return None
- @staticmethod
- def merge_nodes(node1, node2):
- the_node = node1.find_node_with_name(node2.name)
- if not the_node:
- return None
- for child in node2.children:
- n = Node.merge_nodes(the_node, child)
- if not n:
- the_node.add_child(child)
- return the_node
- def merge_with_node(self, another_node):
- # check if this node's name is present in the node or in its children
- node_to_return = Node.from_dict(self.flatten_to_dict())
- x = Node.merge_nodes(node_to_return, another_node)
- return node_to_return
- if __name__ == '__main__':
- data = eval(open('input.txt').read())
- d1 = data['d1']
- d2 = data['d2']
- root_1 = Node.from_dict(d1[0])
- root_2 = Node.from_dict(d2[0])
- Dict1 = map(Node.from_dict, d1)
- Dict2 = map(Node.from_dict, d2)
- # assuming Dict2 should just be one element, then Dict2[0]
- Dict2 = Dict2[0]
- result = []
- # try to merge with every dict in Dict1
- for _dict in Dict1:
- res = _dict.merge_with_node(Dict2)
- result.append(res)
- print result
- $>python test1.py
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement