Python random sequence with seed

后端 未结 2 1248
别那么骄傲
别那么骄傲 2020-12-09 10:10

I\'m doing this for a school project (so I can\'t use any advanced features) and I\'m using Python 2.6.6.

I have a list of numbers from 1 to 1000 and my seed will be

2条回答
  •  清歌不尽
    2020-12-09 10:54

    import random
    SEED = 448
    
    myList = [ 'list', 'elements', 'go', 'here' ]
    random.seed(SEED)
    random.shuffle(myList)
    
    print myList
    

    results in

    ['here', 'go', 'list', 'elements']
    

    Your list is now pseudorandomized.

    'Pseudo' is important, because all lists having the same seed and number of items will return in the same 'random' order. We can use this to un-shuffle your list; if it were truly random, this would be impossible.

    Order = list(range(len(myList)))
    # Order is a list having the same number of items as myList,
    # where each position's value equals its index
    
    random.seed(SEED)
    random.shuffle(Order)
    # Order is now shuffled in the same order as myList;
    # so each position's value equals its original index
    
    originalList = [0]*len(myList)   # empty list, but the right length
    for index,originalIndex in enumerate(Order):
        originalList[originalIndex] = myList[index]
        # copy each item back to its original index
    
    print originalList
    

    results in

    ['list', 'elements', 'go', 'here']
    

    Tada! originalList is now the original ordering of myList.

提交回复
热议问题