mardi 20 décembre 2016

How to shuffle items in list, whilst avoiding any item remaining in the original position?

I have an issue with random.shuffle. Basically, it works just fine in order to pseudo randomize items in list, but in my case I also want to prevent an item from remaining in the same position.

I've came up with this code in order to ensure that every item gets a new position.

match = True
while match is True:
    for i in range(len(initial_list)):
        if initial_list[i]==result_list[i]:
            random.shuffle(result_list)
            match = True
        else:
            match = False

This code passes tests (if shuffle can be done), but is there an easier & faster way to do it?




Aucun commentaire:

Enregistrer un commentaire