Fastest way to get the prefix of a random shuffle in numpy

Viewed 74

As an example, say we want a random 13-card hand from a 52-card deck. We can randomly shuffle all 52 cards and extract the first 13:

    import numpy as np
    cards = np.arange(52)
    rng = np.random.default_rng()
    rng.shuffle(cards)
    hand = cards[:13]

Is there a faster way given that we only need a prefix of the shuffled result? (Including when the array sizes are larger.)

1 Answers

You could randomly choose from the range, without shuffling:

np.random.choice(cards, size=13, replace=False)

#edit:

however, actually timing this:

%%timeit -r 10 -n 10

rng.shuffle(cards)
hand = cards[:13]

The slowest run took 7.99 times longer than the fastest. This could mean that an intermediate result is being cached.
8.14 µs ± 8.42 µs per loop (mean ± std. dev. of 10 runs, 10 loops each)

vs:

%%timeit -r 10 -n 10

np.random.choice(cards, size=13, replace=False)

22.2 µs ± 7.22 µs per loop (mean ± std. dev. of 10 runs, 10 loops each)

vs:

%%timeit -r 10 -n 10

np.random.shuffle(cards)
hand = cards[:13]

3.18 µs ± 699 ns per loop (mean ± std. dev. of 10 runs, 10 loops each)
Related