#PageRank Algorithm using Random Walk !pip install matplotlib import random import matplotlib.pyplot as plt # ----------- Define the link structure (Graph) ------------ pages = { 'Page1': ['Page2', 'Page3'], 'Page2': ['Page3'], 'Page3': ['Page1'], 'Page4': ['Page1', 'Page2', 'Page3'] } # ----------- Initialize counts and parameters ------------ visit_count = {page: 0 for page in pages} num_steps = 100000 damping_factor = 0.85 all_pages = list(pages.keys()) # ----------- Start from a random page ------------ current_page = random.choice(all_pages) for _ in range(num_steps): if random.random() < damping_factor: if pages[current_page]: current_page = random.choice(pages[current_page]) else: current_page = random.choice(all_pages) else: current_page = random.choice(all_pages) visit_count[current_page] += 1 # ----------- Normalize and print PageRanks ------------ print("\n Estimated PageRank (based on visit frequency):") for page in sorted(visit_count): rank = visit_count[page] / num_steps print(f"{page}: {rank:.4f}") # ----------- Optional: Visualize with bar chart ------------ plt.bar(visit_count.keys(), [v / num_steps for v in visit_count.values()], color='skyblue') plt.title('PageRank Estimation via Random Walk') plt.xlabel('Web Pages') plt.ylabel('Estimated PageRank') plt.grid(axis='y') plt.show()