Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - How to input distinct random numbers into a list using loop?

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
like image 720
DGL Avatar asked Feb 13 '26 09:02

DGL


1 Answers

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.

like image 186
harshil9968 Avatar answered Feb 15 '26 22:02

harshil9968