Search code examples
pythonlistshuffle

A good way to shuffle and then unshuffle a python list


So lets say i have a list of tuples

l=[(1,2),(3,4),(5,6),(7,8),(9,10)]

I want to shuffle the values after a specific rule, so that after i shuffle the list i can unshuffle it back using the same method.

One example would be that i shift the entire list to the right with 1 position and then i can shift the shuffled list with one position to the left so i can get the original list.

But this seems kinda simple so i was wondering if they're more creative methods of doing this

Edit: The idea would be that if i send someone the shuffled list, he could unshuffle it without knowing the original list,only knowing the method used for shuffle


Solution

  • You could choose some algorithm to determine a seed that can be derived from the list itself and does not depend on its order.

    For the example data structure, the seed could for instance be the sum of all values. Then with that seed you would generate a random (but deterministic) permutation of the numbers from 0 to n-1. That permutation can then be used as a basis for the shuffle and unshuffle functions:

    import random
    
    def getperm(l):
        seed = sum(sum(a) for a in l)
        random.seed(seed)
        perm = list(range(len(l)))
        random.shuffle(perm)
        random.seed() # optional, in order to not impact other code based on random
        return perm
    
    def shuffle(l):
        perm = getperm(l)
        l[:] = [l[j] for j in perm]
    
    def unshuffle(l):
        perm = getperm(l)
        res = [None] * len(l)
        for i, j in enumerate(perm):
            res[j] = l[i]
        l[:] = res
    

    Example call:

    l=[(1,2),(3,4),(5,6),(7,8),(9,10)]   
    print(l)    
    shuffle(l)
    print(l) # shuffled
    unshuffle(l)
    print(l)  # the original