Reputation: 31
So, I need a code for school where I need to generate 4 random numbers using randint and they can't be duplicates, I just cant seem to get my head around it. - Cheers
Upvotes: 2
Views: 162
Reputation: 15236
We can accomplish a list of 4 random numbers by using a while loop to create a random number then append that number to a list only if that number does not already exist in the list. If we can append list then x -= 1
until x == 0
then the while loop will stop and the code will print out the list.
It will be different every time.
import random
x = 4
list_of_random_numbers = []
while x != 0:
new_random_number = random.randint(0,999) # you can define any range of numbers here.
if new_random_number not in list_of_random_numbers:
list_of_random_numbers.append(new_random_number)
x -= 1
print (list_of_random_numbers)
Edit:
Also as PM 2Ring
said you can just check the length of the list as well:
import random
list_of_random_numbers = []
while len(list_of_random_numbers) < 4:
new_random_number = random.randint(0,999) # you can define any range of numbers here.
if new_random_number not in list_of_random_numbers:
list_of_random_numbers.append(new_random_number)
print (list_of_random_numbers)
Upvotes: 3
Reputation: 403218
Use random.sample
to randomly select 4 elements from a list.
import random
low, high = 0, 1000
w, x, y, z = random.sample(range(low, high) , 4)
Set low
and high
to your desired range from where you want to sample numbers.
Here's a less wasteful solution using randint
(sorry for not seeing this earlier), if you want to generate any number in a wide range.
numbers = set()
while len(numbers) < 4:
num = random.randint(low, high)
if num not in numbers:
numbers.add(num)
w, x, y, z = numbers
Upvotes: 3