How to generate random number with the specific length in python

前端 未结 8 2295
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 13:07

Let say I need a 3 digit number, so it would be something like:

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56


        
相关标签:
8条回答
  • 2020-11-27 13:21

    You could write yourself a little function to do what you want:

    import random
    def randomDigits(digits):
        lower = 10**(digits-1)
        upper = 10**digits - 1
        return random.randint(lower, upper)
    

    Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.

    0 讨论(0)
  • 2020-11-27 13:22

    Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1). If not, random.randint(10**(n-1),10**n-1). And if zero is never allowed, then you'll have to explicitly reject numbers with a zero in them, or draw n random.randint(1,9) numbers.

    Aside: it is interesting that randint(a,b) uses somewhat non-pythonic "indexing" to get a random number a <= n <= b. One might have expected it to work like range, and produce a random number a <= n < b. (Note the closed upper interval.)

    Given the responses in the comments about randrange, note that these can be replaced with the cleaner random.randrange(0,10**n), random.randrange(10**(n-1),10**n) and random.randrange(1,10).

    0 讨论(0)
  • 2020-11-27 13:26

    From the official documentation, does it not seem that the sample() method is appropriate for this purpose?

    import random
    
    def random_digits(n):
        num = range(0, 10)
        lst = random.sample(num, n)
        print str(lst).strip('[]')
    

    Output:

    >>>random_digits(5)
    2, 5, 1, 0, 4
    
    0 讨论(0)
  • 2020-11-27 13:31

    If you want it as a string (for example, a 10-digit phone number) you can use this:

    n = 10
    ''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
    
    0 讨论(0)
  • 2020-11-27 13:32

    If you need a 3 digit number and want 001-099 to be valid numbers you should still use randrange/randint as it is quicker than alternatives. Just add the neccessary preceding zeros when converting to a string.

    import random
    num = random.randrange(1, 10**3)
    # using format
    num_with_zeros = '{:03}'.format(num)
    # using string's zfill
    num_with_zeros = str(num).zfill(3)
    

    Alternatively if you don't want to save the random number as an int you can just do it as a oneliner:

    '{:03}'.format(random.randrange(1, 10**3))
    

    python 3.6+ only oneliner:

    f'{random.randrange(1, 10**3):03}'
    

    Example outputs of the above are:

    • '026'
    • '255'
    • '512'

    Implemented as a function:

    import random
    
    def n_len_rand(len_, floor=1):
        top = 10**len_
        if floor > top:
            raise ValueError(f"Floor {floor} must be less than requested top {top}")
        return f'{random.randrange(floor, top):0{len_}}'
    
    0 讨论(0)
  • 2020-11-27 13:32

    I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)

    import random
    first = random.randint(1,9)
    first = str(first)
    n = 5
    
    nrs = [str(random.randrange(10)) for i in range(n-1)]
    for i in range(len(nrs))    :
        first += str(nrs[i])
    
    print str(first)
    
    0 讨论(0)
提交回复
热议问题