PageRank (power iteration)
Background
PageRank scores the importance of nodes in a directed graph — originally web pages joined by hyperlinks. A node is important if important nodes link to it. The score is the stationary distribution of a "random surfer" who, with probability , follows a random out-link and, with probability , teleports to a uniformly random node. Power iteration finds it by applying the transition repeatedly until it converges.
Problem statement
Implement pagerank(adjacency, damping, num_iterations, tol) returning the PageRank vector. With the column-stochastic transition (where is the probability of moving from node to node ), iterate from the uniform vector :
until or num_iterations steps. A dangling node (no out-links) spreads its mass uniformly.
Input
adjacency— array-like(n, n):adjacency[i][j] = 1if there is an edge .damping—float(default0.85): the damping factor .num_iterations—int(default100): maximum power-iteration steps.tol—float(default1e-6): L1 convergence tolerance.
Output
Returns an np.ndarray of shape (n,): the PageRank scores, which sum to 1.
Examples
Example 1
Input: adjacency = [[0,1,1,0],[0,0,1,0],[1,0,0,0],[0,0,1,0]], damping = 0.85
Output: [0.3725, 0.1958, 0.3941, 0.0375]
Explanation: node 2 receives links from nodes 0, 1, and 3, so the random surfer lands there most often and it earns the largest PageRank.
Constraints
- Build a column-stochastic transition matrix: column spreads over 's out-neighbours; a dangling column becomes uniform .
- Start from the uniform vector and stop on L1 convergence or after
num_iterationssteps. - Returned scores are non-negative and sum to 1.
Notes
- The teleport term guarantees a unique stationary distribution even for disconnected or dangling graphs — it makes the Markov chain irreducible and aperiodic.
- PageRank is the dominant eigenvector of the Google matrix ; power iteration converges because the second-largest eigenvalue is bounded by .
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Ranks form a probability distribution
- •The most-linked-to node has the highest rank
- •A directed cycle gives uniform ranks
- •Deterministic for fixed inputs