Skip to content
Advertisement

Python random module: How can I generate a random number which includes certain digits?

I am trying to generate a random number in Python, but I need it to include certain digits.

Let’s say the range I want for it is between 100000 and 999999, so I want it to be in that range but also include digits like 1, 4, and 5.

Is there a way to do this?

Advertisement

Answer

you can build the number digit by digit

>>> import random
>>> def fun(required=(),size=6):
        result = list(required)
        n = size-len(result)
        result.extend( random.randint(0,10) for _ in range(n)) # fill in the remaining digits
        random.shuffle(result) 
        assert any(result) #make sure that there is at least one non zero digit
        while not result[0]: #make sure that the first digit is non zero so the resulting number be of the required size
            random.shuffle(result)
        return int("".join(map(str,result)))

>>> fun([1,4,5])
471505
>>> fun([1,4,5])
457310
>>> fun([1,4,5])
912457
>>> fun([1,4,5])
542961
>>> fun([1,4,5])
145079
>>> 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement