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
-
Hint: How would you do it with dice?PM 2Ring– PM 2Ring2017-06-10 23:28:45 +00:00Commented Jun 10, 2017 at 23:28
-
3Throw a dice. If its number is equal to any of the other dice, throw it again.Aran-Fey– Aran-Fey2017-06-10 23:33:01 +00:00Commented Jun 10, 2017 at 23:33
-
2@PM2Ring Well I think part of the OP's problem was that he was trying to over-complicate things. Maybe if you would have added a bit more to your hint stating not to over-think things, he might have got it.Chris– Chris2017-06-10 23:43:25 +00:00Commented Jun 10, 2017 at 23:43
-
2@Lewis: No reason to feel stupid here. We all have made some mistakes that are not obvious to us at the time but become clear down the road.Mike - SMT– Mike - SMT2017-06-10 23:45:19 +00:00Commented Jun 10, 2017 at 23:45
-
1Thanks Mountain Tech :) Just getting started, know the basics moving on to slightly more advanced now.Lewis– Lewis2017-06-10 23:50:21 +00:00Commented Jun 10, 2017 at 23:50
2 Answers
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
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)
12 Comments
x to track the count. All of Python's standard collection types store their current length as an attribute, so calling len on them is very efficient. Using a list here is probably no slower than using a set (checking set membership is O(1), but checking list membership is O(n) because it requires a linear scan), but for larger collections, using a set will be faster.