-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpickle_cycle.py
More file actions
63 lines (48 loc) · 1.29 KB
/
Copy pathpickle_cycle.py
File metadata and controls
63 lines (48 loc) · 1.29 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import pickle
class Node:
"""A simple digraph"""
def __init__(self, name):
self.name = name
self.connections = []
def add_edge(self, node):
"""Create an edge between this node and the other"""
self.connections.append(node)
def __iter__(self):
return iter(self.connections)
def preorder_traversal(root, seen=None, parent=None):
if seen is None:
seen = set()
yield (parent, root)
if root in seen:
return
seen.add(root)
for node in root:
recurse = preorder_traversal(node, seen, root)
for parent, subnode in recurse:
yield (parent, subnode)
def show_edges(root):
"""Print all the edges in the graph"""
for parent, child in preorder_traversal(root):
if not parent:
continue
print("{:>5} -> {:>2} ({})".format(parent.name, child.name, id(child)))
# Set up the nodes.
root = Node("root")
a = Node("a")
b = Node("b")
c = Node("c")
# Add edges between them
root.add_edge(a)
root.add_edge(b)
a.add_edge(b)
b.add_edge(a)
b.add_edge(c)
a.add_edge(a)
# Pickle and unpickle the graph to create
# a new set of nodes.
dumped = pickle.dumps(root)
reloaded = pickle.loads(dumped)
print("ORIGINAL GRAPH: ")
show_edges(root)
print("\nRELOADED GRAPH: ")
show_edges(reloaded)