user3712170
user3712170

Reputation: 13

Append non-duplicated random numbers to a list

I want to append 2 random numbers to a list, but it has to check first if the number is not in the list, if it is already in the list it should change it and check again till the numbers are different than the ones in the list.

from random import randrange

def app_rand(lista):
    x=randrange(1,10)
    for i in lista:
        if x==i:
            x=randrange(1,10)
            app_rand(lista)
        else:
            lista.append(x)
    print lista     
app_rand([1,2,3,4,5,6,7])

The list is from 1 to 7 so the unique possible numbers to append should be 9 and 8 and it should append one or the other, this gives me a run time error for maximum recursion exceeded .

Upvotes: 1

Views: 84

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208465

Instead of picking numbers from the entire range and then checking to see if the number you picked is already in the list, it will be more efficient to first filter out all of the numbers that already exist and then pick based on what is left. For example:

import random

def app_rand(lista):
    options = set(range(1, 10)).difference(lista)
    lista.extend(random.sample(options, 2))
    print lista

app_rand([1,2,3,4,5,6,7])

Upvotes: 3

Related Questions