Home > Net >  How to generate a random number between a minimum and maximum number of digits? (Python)
How to generate a random number between a minimum and maximum number of digits? (Python)

Time:12-06

For example, the user could specify a minimum of 2 (two digits) and a maximum of 4 (four digits), and the number would have to be between 10 and 9999. The input is always an integer.

I've managed to do this so that the number always has the maximum number of digits, but I can't figure out how to include the minimum number.

CodePudding user response:

Use random.randint():

import random

min_digits = # enter here
max_digits = # enter here

# This is how you can turn the minimum and maximum number of digits into the range for the final number
min_value = 10**(min_digits - 1)
max_value = (10**max_digits) - 1

# Input these values into the randint function
print(random.randint(min_value, max_value))

CodePudding user response:

The first way that comes to mind is to translate the desired number of digits into integers; i.e. if you want a minimum of 9 digits, then the maximum value of such a number is 999,999,999, because that's the largest 9-digit number. If you want a minimum of 2 digits, then the minimum value of such a number is 10, because that's the smallest 2-digit number.

Having figured that out then you can do:

mindigits = 2
maxdigits = 9

num = random.randrange(10**(mindigits-1), 10**maxdigits)

and get a number in that range.

But a lot of your numbers will be 9 digits and very few will be 2 digits long. In fact, you might think it's always generating long-ish numbers with casual testing. Why? Because there are ten times more 9-digit numbers than there are 8-digit numbers, and ten times more 8-digit numbers than there are 7-digit numbers, and so on. In that range, 2-digit numbers are very rare!

If you want an even distribution of the number of digits, then you can generate the digits individually. The only trick is, the first digit you generate must not be a zero, so you need to generate that from the range 1-9. So we generate that one separately from the rest. We can use a generator expression to generate the other digits, combine everything into a string, and then convert that to an integer.

mindigits = 2
maxdigits = 9

num = int(str(random.randint(1, 9))   "".join(str(random.randint(0, 9)) 
    for _ in range(random.randrange(mindigits-1, maxdigits))))

CodePudding user response:

Use randrange(start, stop).

As a separate matter, you might want an expression like start = 10 ** 2 or stop = 10 ** 4 to describe numbers with a certain number of digits.

CodePudding user response:

Make sure you import the math, random and randint modules/libraries:

random.randint(10,9999)

  • Related