Ranking Pages by Following Links

Eigenvalues & EigenvectorsMedium+20 XP+20

Ranking Pages by Following Links

A search engine wants to rank nnn web pages by importance, where a page is important if important pages link to it. That sounds circular — and an eigenvector is exactly what resolves it.

Picture a surfer clicking around. At every step they:

  • with probability ddd (the damping factor), follow one of the current page's links, chosen uniformly — or, if the page has no links at all, jump to any of the nnn pages uniformly;
  • with probability 1−d1 - d1−d, get bored and jump to any of the nnn pages uniformly.

If rir_iri​ is the probability the surfer is on page iii, one step produces the new scores

rjnew=1−dn  +  d∑i→jriLi  +  d∑i has no linksrinr_j^{\text{new}} = \frac{1-d}{n} \;+\; d\sum_{i \to j} \frac{r_i}{L_i} \;+\; d\sum_{i \text{ has no links}} \frac{r_i}{n}rjnew​=n1−d​+di→j∑​Li​ri​​+di has no links∑​nri​​

where the first sum runs over the pages iii that link to page jjj, and LiL_iLi​ is the number of links on page iii.

That update is a matrix–vector product rnew=G rr^{\text{new}} = G\,rrnew=Gr for one fixed n×nn \times nn×n matrix GGG. The ranking is the score vector that a further step leaves unchanged, G r=rG\,r = rGr=r: an eigenvector of GGG with eigenvalue 111. Every other direction shrinks each time GGG is applied, so you can find it by power iteration — start from equal scores and apply the update again and again.

Task: write pagerank(links, d).

  • links[i] is the list of pages that page i links to. Pages are numbered 0 to n - 1; no page links to itself or lists the same target twice.
  • Start from ri=1/nr_i = 1/nri​=1/n for every page, and repeat the update until no score changes by more than 10−1010^{-10}10−10 in a single step.
  • Return the final scores as a list, each rounded to 4 decimal places.
Markov Chain

Markov Chain Simulator

Observe convergence to the stationary state as the transition matrix powers update the state probability vector over time.

Transition Rates

P(State A → State B)0.30
P(State B → State A)0.40
TRANSITION MATRIX P
[
0.700.300.400.60
]
Rows sum to exactly 1.0
State Transition Diagram
0.300.400.700.60SUNNY ARAINY B
Probability State Distribution
Sunny A:100.00%
Rainy B:0.00%
Transition Steps:0
Stationary Target:[57.1%, 42.9%]
Regardless of which state you start from (Sunny or Rainy), repeated multiplication by the transition matrix converges to the same stationary distribution.

Examples

links = [[1], [2], [0]]
d = 0.85
returns [0.3333, 0.3333, 0.3333]
links = [[1, 2], [2], [0]]
d = 0.85
returns [0.3878, 0.2148, 0.3974]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run