5.15 Compute random subset - why this is wrong?

#1

Why this is wrong?

def random_subset(n: int, k: int) -> List[int]:
    H = {}
    for i in range(k):
        r = random.randrange(i, n)
        if r in H:
            H[i] = H[r], i
        else:
            H[i] = r, i
    return [H[i] for i in range(k)]

Also, why can’t I do this? This also wrong.

def random_subset(n: int, k: int) -> List[int]:
    H = {}
    for i in range(k):
        r = random.randrange(i, n)
        H[r] = H.get(i, i)
        H[i] = H.get(r, r)
    return [H[i] for i in range(k)]
0 Likes