Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a random list of integers, but exclude a certain number?

Tags:

python

random

I'd like to create a random list of numbers in python, but exclude a certain number, k.

I can create a random list of integers: l = [random.randint(0,10) for i in range(5)] Then I can remove the number, k, if it's there, and add another random number in the range, but this seems like too many steps.

In researching this, It's quite easy to find out how to create a random number from a range and exclude a certain number, for example: print (choice([i for i in range(0,9) if i not in [2,5,7]])) I could do this the amount of times I need to create the array -- but this seems more complex than necessary.

Would appreciate some feedback this

like image 426
Katie Melosto Avatar asked Jun 19 '21 18:06

Katie Melosto


2 Answers

Make a list of the numbers in the range, and remove k from the list. Then you can use random.choices() to select multiple elements from the list.

numbers = list(range(0, 11))
numbers.remove(k)
result = random.choices(numbers, k=5)
like image 54
Barmar Avatar answered Sep 27 '22 21:09

Barmar


You could write a generator that yields random numbers of your choosing, and take the first n:

def random_numbers_except(a, b, exclusions):
    while True:
        while (choice := random.randint(a, b)) in exclusions:
            pass
        yield choice

numbers = [number for _, number in zip(range(5), random_numbers_except(0, 10, [2, 5, 7]))
like image 39
L3viathan Avatar answered Sep 27 '22 19:09

L3viathan