简体   繁体   中英

How to generate a range of random numbers in python without repetition

I would like to generate random numbers in the range (0..."MAX"). I would like to make a loop such that every time going through the loop a new unique random number is generated (should not repeat). The loop will continue a total of "MAX" times. There should be "MAX" number of random numbers generated in total. When sorted, the values should be 0..."MAX"; no repetition.

Restrictions: - Assume MAX is much larger than int. (no memory to store all number permutations in memory)

My proposed solution: If I seed the generator from 0...MAX would that allow me to print every unique number between 0 and MAX as in the below function? Assume there's no space to store all numbers and shuffling them.

for x in range (0, MAX):
    random.seed(x)
    num=random.randint(0, MAX)
    print("seed = ",x, "    random number = ", num)

If the answer for the above is yes then would this generation be reversible (can i get the seed from the random number)? In which case would this be considered a kind of block cipher that is if the seed (key) and the range is the same length?

You can do like this:

input = set()
for i in range(MAX):
    input.add(random.randrange(x,y))
print input

with in the range of x and y it will select some random values. W/o repetition means you can use set. so i am adding those values to set.

just make a try this one.

The random module has a sample function , which is predicated on producing unique elements . It is used as in the following example:

random_list = random.sample(xrange(10000000), 60) 
# generates a list of 60 random numbers in the 
# range 0 to 10000000 without repetition

But, do be aware that it will throw an exception if the length of the list is greater than the size of the population, eg

random_list = random.sample(xrange(5), 60 # you will get a ValueError here

If you want to get all the numbers within a particular range,

  1. either we have to store the generated random numbers and compare them against the newly generated random number

    import random result = [] # hash values of numbers between -5 to 256 are the same as the # numbers themselves. So, whatever may be the order, set will have them # in the sorted order. So, `result` cannot be a `set` here. for x in range (0, 10): num = random.randint(0, 10) while num in result: num = random.randint(0, 10) result.append(num) print result
  2. or we can generate the list and shuffle it like this

    data = range(10) import random random.shuffle(data) print data

    since you already have the population as a list and random.shuffle is an in-place operation, the result doesn't have to be stored in a separate list.

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