Skip to content

Commit 3f7bec6

Browse files
bhushan-borolepoyea
authored andcommitted
Added page-rank algorithm implementation (TheAlgorithms#780)
* Added page-rank algorithm implementation * changed init variables
1 parent d8badcc commit 3f7bec6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Diff for: Graphs/pagerank.py

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'''
2+
Author: https://github.com/bhushan-borole
3+
'''
4+
'''
5+
The input graph for the algorithm is:
6+
7+
A B C
8+
A 0 1 1
9+
B 0 0 1
10+
C 1 0 0
11+
12+
'''
13+
14+
graph = [[0, 1, 1],
15+
[0, 0, 1],
16+
[1, 0, 0]]
17+
18+
19+
class Node:
20+
def __init__(self, name):
21+
self.name = name
22+
self.inbound = []
23+
self.outbound = []
24+
25+
def add_inbound(self, node):
26+
self.inbound.append(node)
27+
28+
def add_outbound(self, node):
29+
self.outbound.append(node)
30+
31+
def __repr__(self):
32+
return 'Node {}: Inbound: {} ; Outbound: {}'.format(self.name,
33+
self.inbound,
34+
self.outbound)
35+
36+
37+
def page_rank(nodes, limit=3, d=0.85):
38+
ranks = {}
39+
for node in nodes:
40+
ranks[node.name] = 1
41+
42+
outbounds = {}
43+
for node in nodes:
44+
outbounds[node.name] = len(node.outbound)
45+
46+
for i in range(limit):
47+
print("======= Iteration {} =======".format(i+1))
48+
for j, node in enumerate(nodes):
49+
ranks[node.name] = (1 - d) + d * sum([ ranks[ib]/outbounds[ib] for ib in node.inbound ])
50+
print(ranks)
51+
52+
53+
def main():
54+
names = list(input('Enter Names of the Nodes: ').split())
55+
56+
nodes = [Node(name) for name in names]
57+
58+
for ri, row in enumerate(graph):
59+
for ci, col in enumerate(row):
60+
if col == 1:
61+
nodes[ci].add_inbound(names[ri])
62+
nodes[ri].add_outbound(names[ci])
63+
64+
print("======= Nodes =======")
65+
for node in nodes:
66+
print(node)
67+
68+
page_rank(nodes)
69+
70+
71+
if __name__ == '__main__':
72+
main()

0 commit comments

Comments
 (0)