Problem with the randint function

2

Hello, I'm having a little problem in my code. I try to generate a list of 4 random integers that do not repeat, but ...

list_num = []
c = 0
v = random.randint(0, 9)

while c < 4 and v not in list_num:
    list_num.append(v)
    c += 1
    v = random.randint(0, 9) # O problema está aqui

When attempting to run the v = random.randint(0, 9) line within the loop, content that already existed in the v variable is not replaced by new content generated by the code. I observed this when running it in the python tutor. What could be causing the error?

    
asked by anonymous 23.03.2015 / 17:17

2 answers

3

If you are referring to link , the problem is that it is probably using a fixed seed in your random number generator . My guess is that this is being done so that the results are always deterministic. By chance, the first two calls of random.randint(0,9) returned the same value ( 6 ) for the seed used (1 chance in 10 to happen, and it happened!) And so seemed that the value was not overwritten, when in fact it was.

Try to assign a seed to random yourself, and you should have different results. In my case, I got a list with 4 elements using:

import random
random.seed(10);

list_num = []
c = 0
v = random.randint(0, 9)

while c < 4 and v not in list_num:
    list_num.append(v)
    c += 1
    v = random.randint(0, 9)

You can always, of course, use the clock as a seed, so that the execution is different every time.

And as for the original problem ("generating a list of 4 random integers that do not repeat"), this code needs to be adapted because it is simply stopping when it encounters the first one that repeats itself ... I suggest the following: ( care: if the number of elements you request is greater than the number of elements available, this code will go into an infinite loop)

while c < 4:
    while v in list_num:
        v = random.randint(0, 9)
    list_num.append(v)
    c += 1

I tried the python tutor without using any seed, and got [6, 0, 4, 8] .

    
23.03.2015 / 17:38
2

Save friend, follow code random numbers without reps. I hope it helps you.

import random
lista = []
while len(lista) < 4:
    x = random.randint(1, 50)
    if x not in lista:
        lista.append(x)
lista.sort()     #Aqui ele vai ordenar em crescente do menor para o maior.
print(lista)
    
03.04.2015 / 06:30