Creating a list of random numbers without duplicates in python

so what I am trying to do is create a list of 5 numbers for the game mastermind, and I would like to eliminate all duplicates! The issue is that the code sometimes creates a list with 3 numbers, or 4, or sometimes 5, it seems to be random.

I should also mention we are not allowed to be usin grandom.sample, or random.shuffle

import random

def generatePassword() :
    lis = []
    for i in range(5) :
        #This checks to see if there are duplicate numbers
        r = random.randint(1,9)
        if r not in lis :
            lis.append(r)
        i+=1
    return lis



def main() :
    print(generatePassword())
main()

Upvotes: 2

Views: 22284

Answers (6)

Miriam
Miriam

Reputation: 2721

I do not recommend the solution in this answer - the best option in the standard library is probably random.sample, and there may be more efficient methods using numpy. Both of these options are suggested in other answers.


This method uses random.shuffle to shuffle a list of digits, then selects the first five. This avoids the issue of a theoretically unbounded loop (while len(nums) < 5:), but does not scale well when the range of numbers to choose from (here, 1 to 9) is significantly larger than how many numbers are needed (here, 5).

import random

population = list(range(1, 10))
random.shuffle(population)
print(population[:5])

Upvotes: 2

Rocky Li
Rocky Li

Reputation: 5958

Use numpy.random.permutation if you are looking for method that works and is faster:

import numpy as np
your_list = list(np.random.permutation(np.arange(0,10))[:5])

>>> your_list
[6, 9, 0, 1, 4]

Alternatively, you can use np.random.choice with replace=False:

your_list = list(np.random.choice(np.arange(0,10), 5, replace=False)

Upvotes: 8

SanguineL
SanguineL

Reputation: 1303

So your problem: It won't add the same number twice. But since you use a for i in range(5): it will only repeat 5 times, regardless of if it added a unique number or not.

You need to measure the length of the list, so it will always add 5 random, unique numbers to the list.

You have the code mostly right, but all you need to do is replace: for i in range(5): with: while len(lis) < 5:

Make sure to delete the i += 1 though. It will cause an error if you don't.

Here's the code:

import random

def generatePassword() :
    lis = []
    while len(lis) < 5:
        #This checks to see if there are duplicate numbers
        r = random.randint(1,9)
        if r not in lis :
            lis.append(r)
    return lis



def main() :
    print(generatePassword())
main()

Upvotes: 1

Tezirg
Tezirg

Reputation: 1649

The function random.sample does what you want:

import random

def generatePassword():
    numbers = range(0, 9)
    return random.sample(numbers, 5)

def main() :
    print(generatePassword())
main()

Upvotes: 3

natn2323
natn2323

Reputation: 2081

You don't want to add random, unique integers 5 times; you want to add random, unique integers until your list contains 5 elements. This'll do it:

import random

def generatePassword() :
    lis = []
    while len(lis) < 5:
        #This checks to see if there are duplicate numbers
        r = random.randint(1,9)
        if r not in lis :
            lis.append(r)
    return lis

Upvotes: 2

Pallie
Pallie

Reputation: 1109

Try using a while loop with a condition that checks for the length of lis

while len(lis) < 5:

instead of your for loop

Upvotes: 4

Related Questions