简体   繁体   中英

python randomly generated orders are the same

I tried to generate different random order in N loop, but python seems to generate same sequence. Is the code below correctly written as I am expecting?

import random
import time

def funcA():
    nodeCount = 10               
    order = range(0, nodeCount) 

    random.seed(0x87654321)         
    random.shuffle(order)    

    print("Shuffle order - ")
    print(order)


if __name__ == '__main__':

    cnt = 0
    while cnt < 3:     
#         random.seed(0x87654321) 
        funcA()
        time.sleep(5) 
        cnt += 1

The issue here is in this statement:

random.seed(0x87654321)  

What this does is provide a "seed" value for the random number generator to use as random data. Since the seed is hardcoded right before each call to the shuffle function , the random number generator will behave the same every time.

To fix the issue (and get different results each time you run it), simply remove this statement. If you want to initialize it with the seed, initialize once by doing it outside of the while loop:

if __name__ == '__main__':    
    cnt = 0
    random.seed(0x87654321) 
    while cnt < 3:     
        funcA()
        time.sleep(5) 
        cnt += 1

You're seeding the random number generator with a constant. Any sequence of identical calls to the random number generator with the same seed will produce the same output. If that's not what you want, don't call seed .

只调用一次random.seed(),而不是在随机播放之前每次都调用一次。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM