João Pereira
João Pereira

Reputation: 713

Generate random number in range without specific digits

I've been googling this for some time and haven't found a solution.

I think I can do this with some lines of code but what I'm looking for is a simple (possibly one line) answer.

What I want is to generate a list of numbers between 4000 and 5000 but without certain digits: 7,8 and 9 in my case. Is there any module or function inside random that does this?

Upvotes: 3

Views: 330

Answers (1)

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

Something like this would do.

>>> num = [elem for elem in xrange(4000, 5001) if not {'7', '8', '9'}.intersection(str(elem))]
>>> choice(num)
4210
>>> choice(num)
4640
>>> choice(num)
4102

The comprehension works by creating a set consisting of the strings {'7', '8', '9'} and find the intersection of this set with the set of the digits in our number (generated from 4000 to 5000, both inclusive). If the intersection is empty, then the number does not have any of the digits specified above in which case we should include that and use the list for generating random numbers.

For example,

>>> {'7', '8', '9'}.intersection(str(4555))
set([])
>>> {'7', '8', '9'}.intersection(str(4765))
set(['7'])

Upvotes: 2

Related Questions