home

Nine Algorithms That Changed the Future

PageRank

The Random Surfer Trick

# Imitate a random surfer
# 15% chance the random surfer will pick a random page
# 85% random surfer will follow the link found on the page
import random

# There are 5 pages we want to give scores to, pages 0 to 4
# Every page has a link to some other page given in the dictionary below
page_links = {0: 1, 1: 4, 2: 0, 3: 0, 4: 0}

# Dictionary to hold visit counts
page_visits = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}

curr_page = 0
loop_count = 1000000 # Number of total visits

for i in range(loop_count):
    if random.randint(1, 100) < 15: # Surfer picks a random page
        curr_page = random.randint(0, 4)
    else:
        curr_page = page_links[curr_page] # Surfer follows the link

    page_visits[curr_page] = page_visits[curr_page] + 1 # Increment the visit count for current page

# Print the results
for page in page_visits:
    page_visits[page] = page_visits[page] / loop_count * 100
    print(str(page) + " " + format(page_visits[page], ".2f"))

# Ranking scores for the 5 pages we had based on the links between them
# and the random surf simulation
# 0 33.25
# 1 31.37
# 2 2.83
# 3 2.81
# 4 29.74