What I aim to do is to input 4 distinct numbers into a list called var. If 2 random numbers give the same number, it is not appended, and the loop iterates to pick a new random number. But my code will give only the list of random numbers that are not equal. For example if random numbers generated are 1,4,4,3 my list('var') will only have 1,4,3. ie, only 3 numbers in total. How to correct the code to append a total of 4 unique random numbers into the list?
import random
var=[]
end=4
for i in range(0,end,1):
k=random.randint(0,9)
print k
if k not in var:
var.append(k)
else:
end+=1
So the requirement here is that you keep on doing that operation until your lenght of array is 4, so you can use while len(arr) < 4. Example coded for you :
import random
var=[]
end=4
while len(var) < end:
k=random.randint(0,9)
print k
if k not in var:
var.append(k)
A better way to do this would be random.sample
>>> import random
>>> random.sample(range(0, 9), 4) # xrange is using python 2.7
Read here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With