-
Notifications
You must be signed in to change notification settings - Fork 4
/
graph.py
110 lines (83 loc) · 2.53 KB
/
graph.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# Mirko Mantovani
"""
A weighted undirected graph
"""
class UndirectedGraph:
def __init__(self):
self.graph = {}
def __repr__(self):
return 'Graph:'+ str(self.graph)
def add_node(self, node):
if node not in self.graph:
self.graph[node] = {}
def add_edge(self, i, j, weight):
if i not in self.graph:
self.add_node(i)
if j not in self.graph:
self.add_node(j)
self.graph[i][j] = weight
self.graph[j][i] = weight
def get_edge(self, i, j):
if i in self.graph:
if j in self.graph[i]:
return self.graph[i][j]
return -1
"""
An unweighted directed graph
"""
class DirectedGraph:
def __init__(self):
self.graph = {}
def __repr__(self):
return 'Graph:' + str(self.graph)
def add_node(self, node):
if node not in self.graph:
self.graph[node] = {}
def add_edge(self, i, j):
if i not in self.graph:
self.add_node(i)
self.graph[i][j] = 1
def get_edge(self, i, j):
if i in self.graph:
if j in self.graph[i]:
return self.graph[i][j]
return -1
"""
A directed graph optimized to run fast pagerank algorithm
"""
class OptimizedDirectedGraph:
def __init__(self):
self.graph = {}
# inverted is like an inverted index for graph nodes, it provides fast access to all the nodes pointing to
# the specified pointed whose key is specified
self.inverted = {}
def __repr__(self):
return 'Graph:' + str(self.graph)
def get_len(self):
return len(self.graph)
# get all the nodes pointing to pointed
def get_pointing_to(self, pointed):
if pointed in self.inverted:
return self.inverted[pointed]
else:
return set()
def get_out_degree(self, node):
return len(self.graph[node])
def add_node(self, node):
if node not in self.graph:
self.graph[node] = {}
def add_edge(self, i, j):
if i not in self.graph:
self.add_node(i)
self.graph[i][j] = 1
self.add_inverted(j, i)
def get_edge(self, i, j):
if i in self.graph:
if j in self.graph[i]:
return self.graph[i][j]
return -1
def add_inverted(self, pointed, pointing):
if pointed != pointing:
if pointed not in self.inverted:
self.inverted[pointed] = set()
self.inverted[pointed].add(pointing)