-1

How would I undo the shuffle I have done on alist and bring it back to its original sequence:

[1, 2, 3 , 4]

import random

alist = [1, 2, 3, 4]

random.shuffle(alist)  # alist is randomly shuffled
MarvinJWendt
  • 2,357
  • 1
  • 10
  • 36
mamdooh
  • 19
  • 2

2 Answers2

4

I just took this answer from A good way to shuffle and then unshuffle a python list question's accepted answer and did the small change to it. It's working perfect and please refer @trincot and @canton7 answers for more information, they are very educated.

import random


def getperm(l):
    seed = sum(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):  # [1, 2, 3, 4]
    perm = getperm(l)  # [3, 2, 1, 0]
    l[:] = [l[j] for j in perm]  # [4, 3, 2, 1]


def unshuffle(l):  # [4, 3, 2, 1]
    perm = getperm(l)  # [3, 2, 1, 0]
    res = [None] * len(l)  # [None, None, None, None]
    for i, j in enumerate(perm):
        res[j] = l[i]
    l[:] = res  # [1, 2, 3, 4]


alist = [1, 2, 3, 4]
print(alist)  # [1, 2, 3, 4]

shuffle(alist)
print(alist)  # shuffled, [4, 3, 2, 1]

unshuffle(alist)
print(alist)   # the original, [1, 2, 3, 4]
Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58
0

random.shuffle shuffles the input sequence in-place. To get back the original list, you need to keep a copy of it.

# make a copy
temp = alist[:]
# shuffle
random.shuffle(alist)
# alist is now shuffled in-place
# restore from the copy
alist = temp
rdas
  • 20,604
  • 6
  • 33
  • 46