Click here to Skip to main content
15,917,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So i want to make a list that stores random numbers but the random numbers stored in that list should be unique i have tried writing the program in so many ways but they havent worked i tried sorting the list in ascending order and then look for duplicates and change their values(didnt work)
This is the code i wrote, This code assigns the random value and checks for duplicates while doing that and assigns them a new random value but i still get duplicates:
Python
import random
random_list=[]
for j in range(0,11):
    random_list.append(random.randint(0,11))
    for i in range(0,j):
        while random_list[i]== random_list[j]:
            random_list[i]=random.randint(0,11)
random_list.sort()
print(random_list)


What I have tried:

I have tried doing a thorough dry run through the program but i cant figure out why it doesnt work
Python
import random
random_list=[]
for j in range(0,4):
    random_list.append(random.randint(1,4))
    print("Before: ", random_list)
    for i in range(0,j):
        while random_list[i]== random_list[j]:
            random_list[i]=random.randint(1,4)
        print("After: ",random_list)
random_list.sort()
print(random_list)
Posted
Updated 9-Jul-22 0:38am
Comments
Richard MacCutchan 9-Jul-22 6:29am    
You should check each number before you add it to the list. If it already exists then do not add it.

Something like:
Python
random_list = []
while len(random_list) < 10:
    rnum = random.randint(1,40) # upper limit should be big enough to allow the list to be filled
    if rnum not in random_list:
        random_list.append(rnum)
    else:
        print(F"{rnum} already in") # just for debug purposes
print(random_list)
 
Share this answer
 
The problem with random numbers is that they are just that: random. So you can't guarantee that the next number you draw will not be already in a given set and thus a duplicate. And the problem gets worse as the number of drawn numbers increases - with a big enough sample size, it can become virtually impossible to draw a new number, so your method never ends.

Instead, create a collection with contains all the numbers in the sequence (for a deck of cards for example, that would be 52 entries).
Then draw a number that is 0 or greater, and less than the number of items in the collection.
Use that as an index into the collection, and you have your new number. Remove it from the collection so there is one less item, and you can draw again knowing that you will not get a duplicate.

Make sense?
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900