[Solved] How to do random shuffling in Python?


random.shuffle is your friend, according to the docs

random.shuffle(x[, random]) .
Shuffle the sequence x in place.

import random

#Convert string to list of chars
li = list('ABDEB')

for i in range(5):
    #Shuffle the list, the last shuffled list is shuffled every time
    random.shuffle(li)
    #Convert list to string again and print
    print(''.join(li))

Output might look like

DBEBA
ABEBD
BABDE
BADEB
BDAEB

Or you can start with the same base string every time

import random

for i in range(5):
    li = list('ABDEB')
    random.shuffle(li)
    print(''.join(li))

For shuffle with replacement, you can actually use itertools.combibations_with_replacement and it will give you all possible combinations in one go, then use random.choce to pick an element from there

From the docs:

itertools.combinations_with_replacement(iterable, r)
Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

random.choice(seq)
Return a random element from the non-empty sequence seq.

from itertools import combinations_with_replacement
import random

li = list('ABDEB')

#Get all possible combinations with repetitions
res = [''.join(item) for item in combinations_with_replacement(li,len(li))]

#Use random.choice to pick a element from res
for i in range(5):
    print(random.choice(res))

Output will look like

DDEEE
ABBBE
ADDDD
BBDDB
AADDB

12

solved How to do random shuffling in Python?