How to incrementally sample without replacement?

前端 未结 13 1630
别跟我提以往
别跟我提以往 2020-12-05 00:38

Python has my_sample = random.sample(range(100), 10) to randomly sample without replacement from [0, 100).

Suppose I have sampled n

13条回答
  •  猫巷女王i
    2020-12-05 01:13

    This is my version of the Knuth shuffle, that was first posted by Tim Peters, prettified by Eric and then nicely space-optimized by necromancer.

    This is based on Eric’s version, since I indeed found his code very pretty :).

    import random
    def shuffle_gen(n):
        # this is used like a range(n) list, but we don’t store
        # those entries where state[i] = i.
        state = dict()
        for remaining in xrange(n, 0, -1):
            i = random.randrange(remaining)
            yield state.get(i,i)
            state[i] = state.get(remaining - 1,remaining - 1)
            # Cleanup – we don’t need this information anymore
            state.pop(remaining - 1, None)
    

    usage:

    out = []
    gen = shuffle_gen(100)
    for n in range(100):
        out.append(gen.next())
    print out, len(set(out))
    

提交回复
热议问题