简体   繁体   中英

Inverse of random.shuffle()?

I have a function, for simplicity I'll call it shuffler and it takes an list, gives random a seed 17 and then prints that list shuffled.

def shuffler( n ):
   import random
   random.seed( 17 )
   print( random.shuffle( n ) )

How would I create another function called unshuffler that "unshuffles" that list that is returned by shuffler(), bringing it back to the list I inputted into shuffler() assuming that I know the seed?

Reseed the random generator with the seed in question and then shuffle the list 1, 2, ..., n. This tells you exactly what ended up where in the shuffle.

Here are two functions that do what you need:

import random
import numpy as np

def shuffle_forward(l):
    order = range(len(l)); random.shuffle(order)
    return list(np.array(l)[order]), order

def shuffle_backward(l, order):
    l_out = [0] * len(l)
    for i, j in enumerate(order):
        l_out[j] = l[i]
    return l_out

Example

l = range(10000); random.shuffle(l)
l_shuf, order = shuffle_forward(l)
l_unshuffled  = shuffle_backward(l_shuf, order)

print l == l_unshuffled
#True

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