Generate random numbers in Python without repeating

2

I have the following situation:

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

I have a code that does it 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 want NEVER to generate repeating numbers. For example: [4,4,6,7]

How can I do this?

    
asked by anonymous 06.04.2017 / 04:28

2 answers

5

Just check that the amount drawn does not belong to the list anymore 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)

In 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.

    
06.04.2017 / 05:01
10
import random
result = random.sample(range(0,100), 4)
    
06.04.2017 / 05:32