Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: shuffling list, but keeping some elements frozen

I've such a problem:

There is a list of elements of class CAnswer (no need to describe the class), and I need to shuffle it, but with one constraint - some elements of the list have CAnswer.freeze set to True, and those elements must not be shuffled, but remain on their original positions. So, let's say, for a given list:

[a, b, c, d, e, f]

Where all elements are instances of CAnswer, but c.freeze == True, and for others freeze == False, the possible outcome could be:

[e, a, c, f, b, d]

So element with index 2 is still on its position.

What is the best algorithm to achieve it?

Thank you in advance :)

like image 313
Paweł Sopel Avatar asked Sep 02 '12 17:09

Paweł Sopel


1 Answers

Another solution:

# memorize position of fixed elements
fixed = [(pos, item) for (pos,item) in enumerate(items) if item.freeze]
# shuffle list
random.shuffle(items)
# swap fixed elements back to their original position
for pos, item in fixed:
    index = items.index(item)
    items[pos], items[index] = items[index], items[pos]
like image 175
tobias_k Avatar answered Oct 08 '22 12:10

tobias_k