0

So let's say I have a list of numbers (not a specific range, which could change), and want to generate a random number which excludes the numbers in the list.

List of excluded numbers comes from a sql query.

and the only limit for the random number is the number of digits, which can come from:

random_number = ''.join(random.choice(chars) for _ in range(size))

so I want to generate the random number (with size limit) excluding a list of numbers.

while random_number in exclude_list:
    random_number = ''.join(random.choice(string.digits) for _ in range(size))

Is there a pythonic way (other than using while loop) to do that?

example: generate a 2digit random number which does not exist in a list of numbers like exclude_list=[22,34,56,78]

Mahyar
  • 1,011
  • 2
  • 17
  • 37
  • 1
    How big is the list of excluded numbers? How big is the list of included numbers? – President James K. Polk Jan 13 '17 at 21:43
  • list of excluded numbers comes from a sql query, so not a fixed length. – Mahyar Jan 13 '17 at 21:43
  • I think you need bounds to include too, having a random number from `-infinity` to `+infinity` except for ones in your list would be difficult. – Tadhg McDonald-Jensen Jan 13 '17 at 21:44
  • 2
    You'll stand a better chance of getting useful responses if you show you've put some effort into solving the problem yourself first. If you have, please add what you've tried to the question. – glibdud Jan 13 '17 at 21:44
  • Your edit confused me even more. What is the range from which you want to generate random number? By exclude list due you mean number in the list should be generated as the random number OR the digits in the exclude list should not be the part of randomly generated number? – Moinuddin Quadri Jan 13 '17 at 21:53
  • As mentioned, the only limit is the size of the digit for the random number (so let's say I want to generate a 2 digit random number which doe NOT exist in a list of numbers like exclude=[22,23,56,78]) – Mahyar Jan 13 '17 at 21:57

1 Answers1

6

You may call the random.choice using set to exclude the items in list you do not want to be the part of random selection:

>>> import random

>>> my_list = [1, 2, 3, 4, 5, 6, 7]
>>> exclude_list = [3, 6, 7]

# list containing elements from `my_list` excluding those of `exclude_list`
>>> valid_list = list(set(my_list) - set(exclude_list))

>>> random.choice(valid_list)
5  # valid random number
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126