Random string generation with upper case letters and digits

前端 未结 30 3591
逝去的感伤
逝去的感伤 2020-11-22 02:51

I want to generate a string of size N.

It should be made up of numbers and uppercase English letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4
30条回答
  •  一个人的身影
    2020-11-22 03:18

    Two methods :

    import random, math
    

    def randStr_1(chars:str, length:int) -> str:
        chars *= math.ceil(length / len(chars))
        chars = letters[0:length]
        chars = list(chars)
        random.shuffle(characters)
    
        return ''.join(chars)
    

    def randStr_2(chars:str, length:int) -> str:
        return ''.join(random.choice(chars) for i in range(chars))
    


    Benchmark :

    from timeit import timeit
    
    setup = """
    import os, subprocess, time, string, random, math
    
    def randStr_1(letters:str, length:int) -> str:
        letters *= math.ceil(length / len(letters))
        letters = letters[0:length]
        letters = list(letters)
        random.shuffle(letters)
        return ''.join(letters)
    
    def randStr_2(letters:str, length:int) -> str:
        return ''.join(random.choice(letters) for i in range(length))
    """
    
    print('Method 1 vs Method 2', ', run 10 times each.')
    
    for length in [100,1000,10000,50000,100000,500000,1000000]:
        print(length, 'characters:')
    
        eff1 = timeit("randStr_1(string.ascii_letters, {})".format(length), setup=setup, number=10)
        eff2 = timeit("randStr_2(string.ascii_letters, {})".format(length), setup=setup, number=10)
        print('\t{}s : {}s'.format(round(eff1, 6), round(eff2, 6)))
        print('\tratio = {} : {}\n'.format(eff1/eff1, round(eff2/eff1, 2)))
    

    Output :

    Method 1 vs Method 2 , run 10 times each.
    
    100 characters:
        0.001411s : 0.00179s
        ratio = 1.0 : 1.27
    
    1000 characters:
        0.013857s : 0.017603s
        ratio = 1.0 : 1.27
    
    10000 characters:
        0.13426s : 0.151169s
        ratio = 1.0 : 1.13
    
    50000 characters:
        0.709403s : 0.855136s
        ratio = 1.0 : 1.21
    
    100000 characters:
        1.360735s : 1.674584s
        ratio = 1.0 : 1.23
    
    500000 characters:
        6.754923s : 7.160508s
        ratio = 1.0 : 1.06
    
    1000000 characters:
        11.232965s : 14.223914s
        ratio = 1.0 : 1.27
    

    The performance of first method is better.

提交回复
热议问题