Generate random numbers in Python without repeating
I have the following situation:
I have a vector with 4 indexes. Each index generates a random value from 0 to 100.
I have a code that does this perfectly, however, sometimes the numbers repeat themselves.
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 this?
4 answers
You can implement the algorithm this way...
from random import sample
sorteados = sample(range(0, 100), 4)
print(sorteados)
Note that in this code we are using the sample method from the random
library. With this method we can draw a number of values without repeating each other.
import random
result = random.sample(range(0,100), 4)
Just check if the drawn value no longer belongs to the list, and if it belongs, 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 the same is no longer in the list.
If you are working with dictionaries in python:
aleatorio = randint(1, 6)
test = NomeDict.values()
if aleatorio not in test:
NomeDict.update({chave: valor})