Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65840217/duplicate-number-generated-when-using-python-random-module

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...