0

Is there a way where we can shuffle a list in python and reverse it if we needed for eg a = [1,2,3,4,'a','b','D','#'] and make it as 4aD#1b23 random which can be later reversed as it was in the list like [1,2,3,4,'a','b','D','#']

I tried to make a reference number which will be used to reverse it but not got any exact solution for it you have please let me know.

  • just use shuffle method from the random library: `from random import shuffle shuffle(list) print(list)` – Adrien Derouene Apr 24 '23 at 08:37
  • but using it cannot be reversed i want to know method to reverse the list after shuffle – Suroj Sapkota Apr 24 '23 at 08:41
  • 2
    Could you be more specific? What do you want to use for this? Is there a reason you can't simply copy the original list? – Jasmijn Apr 24 '23 at 08:45
  • 1
    This seems a bit like an XY problem to me, and depending on the context there may be different good solutions, e.g. just keeping a copy of the original list, or shuffling and later sorting `(index, item)` pairs generated with `enumerate`, or recreating the original order based on some heuristic (e.g. "first sorted numbers, then sorted strings"), or something entirely different. – tobias_k Apr 24 '23 at 08:52
  • Maybe you want to identify a randomly-chosen permutation of N items? – khelwood Apr 24 '23 at 08:55
  • 1
    Might be useful [How do I un-shuffle a list back to its original form](https://stackoverflow.com/a/57341086/12575557) – Jorge Luis Apr 24 '23 at 09:13

1 Answers1

3

You can implement a shuffle function yourself using the Fisher-Yates algorithm for example, in which case you can use your own seeded random number generator. You can then implement another unshuffle algorithm using the same seeded RNG. I've adapted my answer where I've done this previously to Python:

import random


def seeded_shuffle(l, seed):
    rng = random.Random(seed)
    for i in range(len(l) - 1, -1, -1):
        j = rng.randint(0, i)
        l[i], l[j] = l[j], l[i]


def seeded_unshuffle(l, seed):
    rng = random.Random(seed)
    indices = [rng.randint(0, i) for i in range(len(l) - 1, -1, -1)]

    for i, j in enumerate(indices[::-1]):
        l[i], l[j] = l[j], l[i]


a = [1, 2, 3, 4, 'a', 'b', 'D', '#']
seed = 42

seeded_shuffle(a, seed)
print(a)  # [4, 'a', 'D', '#', 3, 'b', 1, 2]

seeded_unshuffle(a, seed)
print(a)  # [1, 2, 3, 4, 'a', 'b', 'D', '#']
deceze
  • 510,633
  • 85
  • 743
  • 889