================================================================================
EXPERIMENT 9: SIMPLE PAGERANK (WITHOUT DAMPING FACTOR) & HITS ALGORITHM
Formula: PR(A) = Sum( PR(T) / C(T) )  or  v_k = A * v_{k-1}
================================================================================

--------------------------------------------------------------------------------
1. SIMPLE PAGERANK WITHOUT DAMPING FACTOR (30 Lines)
--------------------------------------------------------------------------------
GRAPH = {
    'A': ['B', 'C'],
    'B': ['D'],
    'C': ['A', 'B', 'D'],
    'D': ['C']
}
MAX_ITER = 20

nodes = sorted(list(GRAPH.keys()))
N = len(nodes)
pr = {n: 1.0 / N for n in nodes}  # Uniform initial rank: 1/N

for it in range(1, MAX_ITER + 1):
    new_pr = {n: 0.0 for n in nodes}
    # Dangling node share (nodes with 0 outgoing links)
    dangling_share = sum(pr[n] for n in nodes if len(GRAPH[n]) == 0) / N
    
    # Distribute rank: PR(A) = Sum( PR(T) / C(T) )
    for n in nodes:
        out = GRAPH[n]
        if out:
            share = pr[n] / len(out)
            for target in out:
                new_pr[target] += share
                
    pr = {n: new_pr[n] + dangling_share for n in nodes}

print("Final PageRank Scores:")
for p, s in sorted(pr.items(), key=lambda x: x[1], reverse=True):
    print(f"Page {p} -> {s:.4f} ({s*100:.1f}%)")

--------------------------------------------------------------------------------
2. HITS ALGORITHM (HUBS & AUTHORITIES) (35 Lines)
--------------------------------------------------------------------------------
import math
GRAPH = {'A': ['B', 'C'], 'B': ['C'], 'C': ['A'], 'D': ['C']}
nodes = sorted(list(GRAPH.keys()))
in_links = {n: [src for src in nodes if n in GRAPH[src]] for n in nodes}

h = {n: 1.0 for n in nodes}
a = {n: 1.0 for n in nodes}

for _ in range(10):
    # Authority = sum of hubs pointing to it
    new_a = {p: sum(h[q] for q in in_links[p]) for p in nodes}
    norm_a = math.sqrt(sum(v**2 for v in new_a.values()))
    a = {p: new_a[p] / norm_a for p in nodes}
    
    # Hub = sum of authorities it points to
    new_h = {p: sum(a[q] for q in GRAPH[p]) for p in nodes}
    norm_h = math.sqrt(sum(v**2 for v in new_h.values()))
    h = {p: new_h[p] / norm_h for p in nodes}

print("Final Authorities:", {k: round(v, 4) for k, v in a.items()})
print("Final Hubs:", {k: round(v, 4) for k, v in h.items()})
