-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcopy_recursion.py
More file actions
41 lines (33 loc) · 1.15 KB
/
copy_recursion.py
File metadata and controls
41 lines (33 loc) · 1.15 KB
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
41
import copy
class Graph:
def __init__(self, name, connections):
self.name = name
self.connections = connections
def add_connection(self, other):
self.connections.append(other)
def __repr__(self):
return "Graph(name={}, id={})".format(self.name, id(self))
def __deepcopy__(self, memodict):
print("\nCalling __deepcopy__ for {!r}".format(self))
if self in memodict:
existing = memodict.get(self)
print("Already copied to {!r}".format(existing))
return existing
print("Memo dictionary: ")
if memodict:
for k, v in memodict.items():
print("{}: {}".format(k, v))
else:
print("(empty)")
dup = Graph(copy.deepcopy(self.name, memodict), [])
print("Copying to new object {}".format(dup))
memodict[self] = dup # Cache for reuse
for c in self.connections:
dup.add_connection(copy.deepcopy(c, memodict))
return dup
root = Graph("root", [])
a = Graph("a", [root])
b = Graph("b", [a, root])
root.add_connection(a)
root.add_connection(b)
dup = copy.deepcopy(root)