Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get n unique numbers uniformly from a given range?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading