2

I would like to create a function that returns a list of unique random numbers having a min and max amount of digits.

I could use sample of random to create a list of unique random numbers but I have to pass a range. I would like to modify it to pass a min and max amount of digits.

For example min amount of digits is 1 and max amount of digits is 4

So it should create a random number in the range of (0, 9999)

Or if the min and max are both 1 it should create a list of random unique numbers in the range of (0, 9)

I was trying to do

from random import sample

sample(range(x,y), k)

But my problem is now how to convert the min and max amount of digits to a range

91DarioDev
  • 1,612
  • 1
  • 14
  • 31

3 Answers3

2

Using power of 10, you'll reach this easily

  • 10 ** (min_d - 1) will values 1, 10, 100, ...
  • 10 ** max_d will values 9, 99, 999, ... as the upper bound of range is exclusive
min_d = 2
max_d = 5
result = sample(range(10 ** (min_d - 1), 10 ** max_d), 10)

# Use the following if you're unsunre of the bounds
print(10 ** (min_digit - 1)) # 10
print(10 ** max_digit - 1)   # 99999
azro
  • 53,056
  • 7
  • 34
  • 70
2

"But my problem is now how to convert the min and max amount of digits to a range"

Say min_dig = 1 and max_dig = 4:

>>> low = 10**(min_dig - 1) if min_dig>1 else 0
>>> low
0
>>> high = 10**(max_dig) - 1
>>> high
9999
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
1

Either convert string to int, or you may use directly orders of digit,

>>> foo = lambda x, y: range(int('0'*x), int('9'*y))
>>> sample(foo(1, 4), 3)
[1440, 6542, 1731]
>>> sample(foo(1, 1), 3)
[3, 5, 8]

For other way, foo can be like this:

foo = lambda x, y: range(10**(x-1) - 1, 10**(y)-1)
Vicrobot
  • 3,795
  • 1
  • 17
  • 31