Advertisement
okpalan

pagerank.py

Nov 9th, 2023 (edited)
595
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | Source Code | 0 0
  1. def compute_pagerank(graph, damping_factor=0.85, max_iterations=100):
  2.     """
  3.    Compute the PageRank of each node in the graph.
  4.    
  5.    Parameters
  6.    ----------
  7.    graph : dict
  8.        A dictionary representing the structure of the graph. The keys are
  9.        the nodes in the graph, and the values are a list of the nodes that
  10.        are connected to that node.
  11.    damping_factor : float
  12.        The damping factor for the PageRank algorithm.
  13.    max_iterations : int
  14.        The maximum number of iterations to perform before stopping.
  15.    
  16.    Returns
  17.    -------
  18.    dict
  19.        A dictionary mapping each node in the graph to its PageRank score.
  20.    """
  21.    
  22.     # Check for invalid damping factor
  23.     if damping_factor <= 0 or damping_factor >= 1:
  24.         raise ValueError("Invalid damping factor")
  25.    
  26.     # Initialize the PageRank of each node to 1
  27.     pagerank = {node: 1 for node in graph.keys()}
  28.    
  29.     # Perform the PageRank algorithm for the given number of iterations
  30.     for _ in range(max_iterations):
  31.         for node in graph.keys():
  32.            
  33.             # Compute the sum of the PageRank scores of the nodes that are
  34.             # connected to this node
  35.             pagerank_sum = 0
  36.             for neighbor in graph[node]:
  37.                 pagerank_sum += pagerank[neighbor]
  38.            
  39.             # Update the PageRank of this node
  40.             pagerank[node] = (1 - damping_factor) + \
  41.                 (damping_factor * pagerank_sum)
  42.    
  43.     return pagerank
  44.  
  45. driver code.
  46.  
  47.  
  48. # Create a graph
  49. graph = {
  50.     "A": ["B", "C"],
  51.     "B": ["A", "C", "D"],
  52.     "C": ["A", "B", "D", "E"],
  53.     "D": ["B", "C", "E", "F"],
  54.     "E": ["C", "D"],
  55.     "F": ["D"]
  56. }
  57.  
  58. # Compute the PageRank scores
  59. pagerank = compute_pagerank(graph)
  60.  
  61. # Print the PageRank scores
  62. for node, score in pagerank.items():
  63.     print(node, ":", score)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement