Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!-*- coding: utf-8 -*-
- '''
- @author : Hasan Mahmud Tuhin
- 19CS-JD14M
- @Description:
- This code finds page rank of a graph using power iteration method.
- '''
- class PageRank:
- def __init__(self,n):
- self.epsilone = 0.000000000001
- self.Node = n
- self.matrix = [ [0] * self.Node ] * self.Node;
- print(self.matrix)
- self.rank =[]
- self.old_rank = [0] * self.Node
- for i in range(0,self.Node):
- self.rank.append( 1 / self.Node)
- #self.old_rank.append(1/self.Node)
- def iteration(self):
- try:
- product = []
- for i in range(0,self.Node):
- self.old_rank[i] = self.rank[i]
- product.append(0)
- #- begain multiplication
- for i in range(0,self.Node):
- for j in range(0,self.Node):
- product[i] += self.matrix[i][j] * self.rank[j]
- #-- copy rank matrix
- for i in range(0,self.Node):
- self.rank[0] = product[0]
- except Exception as e:
- print("Error on calculation power iteration .{}".format(e))
- def stop(self):
- try:
- for i in range(0,self.Node):
- if abs(self.rank[i] - self.old_rank[i]) < self.epsilone:
- continue
- else:
- return False
- return True
- except:
- pass
- def input_values(self):
- try:
- print("Enter values of Matrix");
- for i in range(0,self.Node):
- #self.matrix[i].append([])
- for j in range(0,self.Node):
- print("Enter value for matrix[{}][{}] : ".format(i,j),end='');
- self.matrix[i][j] = float( input() )
- except Exception as e:
- print("Error in input. {}".format(e))
- def show_rank(self):
- try:
- print("\nPage Rank is :\n")
- for i in range(0,self.Node):
- print("[{}]".format(self.rank[i]))
- except:
- pass
- def show_old(self):
- print("old Rank matrix is: ")
- for i in range(0,self.Node):
- print("[{}]".format(self.old_rank[i]))
- if __name__ == "__main__":
- print("Enter Number of Nodes")
- N = int(input())
- pg = PageRank(N)
- pg.input_values()
- #-- do iteration 50 times, if no difference between two
- #--- iteration then break
- for i in range(0,50):
- pg.iteration()
- print("{} Iteration Done".format(i));
- if pg.stop():
- print("Stop, Because Two interation are same")
- break
- pg.show_rank()
- #pg.show_old()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement