forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpage_rank.py
71 lines (50 loc) · 1.44 KB
/
page_rank.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
"""
Author: https://github.com/bhushan-borole
"""
"""
The input graph for the algorithm is:
A B C
A 0 1 1
B 0 0 1
C 1 0 0
"""
graph= [[0, 1, 1], [0, 0, 1], [1, 0, 0]]
classNode:
def__init__(self, name):
self.name=name
self.inbound= []
self.outbound= []
defadd_inbound(self, node):
self.inbound.append(node)
defadd_outbound(self, node):
self.outbound.append(node)
def__repr__(self):
returnf"<node={self.name} inbound={self.inbound} outbound={self.outbound}>"
defpage_rank(nodes, limit=3, d=0.85):
ranks= {}
fornodeinnodes:
ranks[node.name] =1
outbounds= {}
fornodeinnodes:
outbounds[node.name] =len(node.outbound)
foriinrange(limit):
print(f"======= Iteration {i+1} =======")
for_, nodeinenumerate(nodes):
ranks[node.name] = (1-d) +d*sum(
ranks[ib] /outbounds[ib] foribinnode.inbound
)
print(ranks)
defmain():
names=list(input("Enter Names of the Nodes: ").split())
nodes= [Node(name) fornameinnames]
forri, rowinenumerate(graph):
forci, colinenumerate(row):
ifcol==1:
nodes[ci].add_inbound(names[ri])
nodes[ri].add_outbound(names[ci])
print("======= Nodes =======")
fornodeinnodes:
print(node)
page_rank(nodes)
if__name__=="__main__":
main()