Generate random numbers in Python without repeating

Asked

Viewed 16,556 times

7

I have the following situation:

I have a vector with 4 indexes. In each index a random value is generated from 0 to 100.

I have a code that does this perfectly, but sometimes the numbers repeat.

Below the code:


from random import randint

AP_X = [randint(0, 100), randint(0, 100), randint(0, 100), randint(0, 100)]
print AP_X

I wish that NEVER repeated numbers are generated. For example: [4,4,6,7]

How can I do that?

4 answers

14

import random
result = random.sample(range(0,100), 4)
  • Thank you! It worked correctly.

7

Just check if the drawn value no longer belongs to the list, and if it does, draw another one. Something like:

result = []
while len(result) != 4:
    r = randint(0, 100)
    if r not in result:
        result.append(r)

This way the code is executed until the list has 4 elements and only a new one is inserted when it is no longer in the list.

  • Thank you! It worked perfectly.

  • Why not store the values in a set and then turn it into a list?

  • 1

    @Germanobarcelos because you do not guarantee that there will be 4 different values

3


For you to draw 4 values within the range [0, 100], without repetitions, you need to implement the range(0, 101), using the method sample library Random.

Then the code can be assembled as follows:

from random import sample

sorteados = sample(range(0, 101), 4)
print(sorteados)

This way we can draw lots 4 values among the range(0, 101) unrepeated.

-1

If you are working with python dictionaries:

aleatorio = randint(1, 6)
test = NomeDict.values()

if aleatorio not in test:
    NomeDict.update({chave: valor})
  • 3

    It makes no sense as an answer, the questioner just wants a list of four random numbers between zero and a hundred that do not recur random.sample(range(0,100), 4).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.