import randomimport bisectdef weighted_choice(weights): totals = [] running_total = 0 for w in weights: running_total += w totals.append(running_total) rnd = random.random() * running_total idx = bisect.bisect_right(totals, rnd) return idxdef weighted_sample(weights, n): op_weights = [i for i in weights] idxs = [] for _ in range(n): i = weighted_choice(op_weights) idxs.append(i) op_weights[i] = 0 return idxsprint weighted_sample([1, 2, 1000000, 3, 54, 54, 567, 7], 3)