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 :)
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With