random.choice() returns same value at the same second, how does one avoid it?

后端 未结 3 1797
借酒劲吻你
借酒劲吻你 2021-01-11 10:11

I have been looking at similar questions regarding how to generate random numbers in python. Example: Similar Question - but i do not have the problem that the randomfunctio

3条回答
  •  无人及你
    2021-01-11 10:19

    def getRandomID(n):
    
        import datetime
        import random
    
        random.seed(datetime.datetime.now())
    
        letters = "abcdefghiklmnopqrstuvwwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    
        idList = [ ''.join([random.choice(letters) for j in range(1,36)]) for i in range(n)]
    
        return idList
    

    this script in the 3rd test of 10 million ids again have made them all unique

    changing for loop to list comprehension did speedup quite a bit.

    >>> listt = getRandomID(10000000)
    >>> print(len(listt))
    10000000
    
    >>> setOfIds = set(listt)
    >>> print(len(setOfIds))
    10000000
    

    this script uses permutations with repetition: 62 choose 35, to theoretically total number of ids is quite big it is pow(62,35)

    541638008296341754635824011376225346986572413939634062667808768
    

提交回复
热议问题