-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcentrality.py
More file actions
51 lines (47 loc) · 1.24 KB
/
centrality.py
File metadata and controls
51 lines (47 loc) · 1.24 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
#
# Write centrality_max to return the maximum distance
# from a node to all the other nodes it can reach
#
def centrality_max(G, v):
open = [v]
distanceFromStart = {}
distanceFromStart[v] = 0
while open:
current = open.pop(0)
for neighbor in G[current]:
if neighbor not in distanceFromStart:
distanceFromStart[neighbor] = distanceFromStart[current] + 1
open.append(neighbor)
# print distanceFromStart
result = max(distanceFromStart.values())
# print result
return result
#################
# Testing code
#
def make_link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = 1
if node2 not in G:
G[node2] = {}
(G[node2])[node1] = 1
return G
def test():
chain = ((1,2), (2,3), (3,4), (4,5), (5,6))
G = {}
for n1, n2 in chain:
make_link(G, n1, n2)
assert centrality_max(G, 1) == 5
assert centrality_max(G, 3) == 3
tree = ((1, 2), (1, 3),
(2, 4), (2, 5),
(3, 6), (3, 7),
(4, 8), (4, 9),
(6, 10), (6, 11))
G = {}
for n1, n2 in tree:
make_link(G, n1, n2)
assert centrality_max(G, 1) == 3
assert centrality_max(G, 11) == 6
test()