How to generate random numbers that are different? [duplicate]

旧城冷巷雨未停 提交于 2020-01-26 11:36:47

问题


Possible Duplicate:
pick N items at random

I need to generate 6 random numbers between 1 and 49, but they cannot be the same. I know how to do make them random, I just am not sure how to ensure that they are different.

The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help.

Any advice is greatly appreciated.


回答1:


You can use random.sample:

>>> random.sample(xrange(1,50), 6)
[26, 39, 36, 46, 37, 1]

"The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help."

Assuming this is an assignment and you need to implement the sampling yourself, you could take a look at how random.sample is implemented. It's really informative, but may be too complicated for your needs since the code also ensures that all sub-slices will also be valid random sample. For efficiency, it also uses different approaches depending on the population size.

As for the worksheet, I believe it assumes you're starting off with a list of numbers from 1 to 49 and suggests that you replace numbers that you're selected with 0 so there can be skipped if reselected. Here's some pseudo code to get you started:

population = range(1, 50)  # list of numbers from 1 to 49
sample = []
until we get 6 samples:
  index = a random number from 0 to 48  # look up random.randint()
  if population[index] is not 0:  # if we found an unmarked value
    append population[index] to sample
    set population[index] = 0  # mark selected

If you wish to attempt something different, there are many other approaches to consider e.g. randomising the list then truncating, or some form of reservoir sampling.

Good luck with your assignment.




回答2:


A set will not keep any duplicates:

s = set()
while len(s) < 6:
    s.add(get_my_new_random_number())



回答3:


It is a very common and stupid interviews question, here is its solution/algorithm:

import random
a = range(1,50)
for i in xrange(6):
    b = a[random.randint(0,len(a)-i)]
    a.remove(b)
    print b

For the people cared about the efficiency here is the test bench of my solution and Chin's:

>>> random.sample(xrange(1,50), 6)
[26, 39, 36, 46, 37, 1]

The results:

>python -mtimeit -s'import try2'
[38, 7, 31, 24, 30, 32]
100000000 loops, best of 3: 0.0144 usec per loop
>python -mtimeit -s'import try1'
36
26
41
31
37
14
100000000 loops, best of 3: 0.0144 usec per loop

resolved to be the same time!



来源:https://stackoverflow.com/questions/13628725/how-to-generate-random-numbers-that-are-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!