How to generate random numbers that are different?

Possible duplicate:
select N items randomly

I need to generate 6 random numbers from 1 to 49, but they cannot be the same. I know how to make them random, I'm just 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 this will help.

Any advice is appreciated.

+13
source share
3 answers

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 this will help."

, , , , random.sample . , , , - . .

, , , 1 49 , 0, , . , :

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

- , , . , , .

.

+36

A set :

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

, /:

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 people who care about efficiency, here is the test bench for my solution and Chin's:

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

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

decided to be the same!

+3
source

Source: https://habr.com/ru/post/1543598/


All Articles