I am trying to swap nodes between two binary trees, which are represented as nested dicts. I have tried to accomplish this by using a function that takes in a dict and list of keys, performs a deep get on it, and returns the nested dict. e.g.
def deep_get(dictionary, keys, default=None):
""" By Yuda Prawira
Source: https://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary"""
return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
However whenever I assign it to a variable and try to do a basic swap, the original dict is unchanged:
a = deep_get(tree1, "left.right.left")
b = deep_get(tree2, "left.right")
c = a.copy()
a.clear()
a.update(b)
b.clear()
b.update(c)
Is there a simpler way of accomplishing this, or will I have to create a tree class that wraps around the dict?
sample input:
tree1 = {'left': {'left': 5, 'op': 'sin', 'right': 1}, 'op': 'cos', 'right': {'op': 'sin', 'right': 3}}
tree2 = {'left': {'left': 1, 'op': 'sin', 'right': 2}, 'op': 'tan', 'right': {'left': 1, 'op': 'sin', 'right': 4}}
First, I choose randomly a node from tree1 and tree2 to swap. Suppose I want to swap the first level left branch of tree1 with the second level right branch of tree2. Then the trees after swap should be like:
tree1 = {'left': {'left': 1, 'op': 'sin', 'right': 4}, 'op': 'cos', 'right': {'op': 'sin', 'right': 3}}
tree2 = {'left': {'left': 1, 'op': 'sin', 'right': 2}, 'op': 'tan', 'right': {'left': 5, 'op': 'sin', 'right': 1}}