Home > Back-end >  How to get n unique numbers uniformly from a given range?
How to get n unique numbers uniformly from a given range?

Time:09-08

I have a integer range [0, Z). I need to obtain n (where n <= Z) random numbers from this range, but they have to be unique. So I know I can just code up rejection sampling to do this, but I'm wondering if there's a one line python function that can do this for me?

CodePudding user response:

why not use random sampling without replacement

import numpy as np

n = 25
a = range(26)
out = np.random.choice(a, size=n, replace=False)
len(np.unique(out))
>>>25
  • Related