简体   繁体   中英

choosing non-equal random integers from an array (python)

I'm very new to python. I need to pull 5 random numbers between 1 and 100. However, these five numbers cannot be the same. I was thinking about creating a vector (range (1, 101)) and pulling random values from the vector, and then creating an loop that says if the second draw is equal to the first then draw another random number and if the draw after that is equal to the previous two draw again, etc. until 5 non-equal random numbers are pulled. Is there a more elegant way to do this?

Use random.sample :

>>> from random import sample
>>> sample(range(1, 101), 5)
[86, 90, 20, 72, 49]

What you want is a variation on the Fisher-Yates shuffle . I don't 'do' python (I'm a Java person by preference), but, it's quite simple....

create an array of your source 'set' (the array from 1 to 101), in an ordered fashion.

Then what you do is set a variable last to the array.size - 1 , and do the following:

int[] ret = new int[5] // return array of 5 members.
for (int i = 0; i < 5; i++) { // 5 is the number of values you want.
    int rand = random(last + 1) // get a random integer from 0 to last (includes last)
    # put the value at array[rand] in your return array var
    ret[i] = array[rand]
    # move the value at the end to the value we just copied out:
    array[rand] = array[last]
    # decrease the size of the values we can select from:
    last--;
}

This way you get to select 5 random values from your set. No duplcicates, all with the same probability.

A full Fisher-yates shuffle can do this for the entire array, in-place. I am just using a part of the algorithm that you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM