If you are referring to the site http://www.pythontutor.com/, The problem is that he’s probably using a fixed seed in his random number generator. My guess is that this is being done so that the results are always deterministic. By chance, the first two calls to random.randint(0,9)
returned the same value (6
) for the seed used (1 in 10 chance of happening, and it happened!) and so seemed that the value was not overwritten, when in fact it was.
Try assigning a seed to the random
, 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 finds the first one that repeats... I suggest the following: (caring for: if the number of elements you ask for is greater than the number of elements available, this code will enter an infinite loop)
while c < 4:
while v in list_num:
v = random.randint(0, 9)
list_num.append(v)
c += 1
I tried it on python tutor without using any seed, and I obtained [6, 0, 4, 8]
.
I ran this code in the shell, and it worked smoothly (ex.:
[8, 0, 2, 9]
). Probably the problem is in python tutor... (there is also a 10 chance that the second value will be identical to the first one however, but that’s not the case) I ran the code twice in pythontutor.com and had6
in both - showing that it is probably not generating random numbers as it should. The reason for this I do not know.– mgibsonbr