Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to random shuffle a list where each variable will end up in a new place [duplicate]

I would like to random shuffle a list so that each variable in the list when shuffled gets put in a new place in the list.

What I am currently doing:

list = ['a', 'b','c', 'd'];
random.shuffle(list)

list
['c','b','d','a']

With this method I shuffle the list but it is still possible to have a variable end up in the same place in this case 'b'.

My desired output

completely shuffled list

['c','a','d','b']

I appreciate any help. I am new to python but please let me know if any further information is needed.

like image 383
Dre Avatar asked Dec 06 '16 23:12

Dre


1 Answers

Something like this should do what you want:

import random
import copy

def super_shuffle(lst):
    new_lst = copy.copy(lst)
    random.shuffle(new_lst)
    for old, new in zip(lst, new_lst):
        if old == new:
            return super_shuffle(lst)

    return new_lst

Example:

In [16]: super_shuffle(['a', 'b', 'c'])
Out[16]: ['b', 'c', 'a']
like image 82
Jack Avatar answered Oct 26 '22 17:10

Jack