Python: shuffling list, but keeping some elements frozen

后端 未结 5 710
隐瞒了意图╮
隐瞒了意图╮ 2021-01-08 00:25

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 -

5条回答
  •  粉色の甜心
    2021-01-08 00:53

    In linear time, constant space using random.shuffle() source:

    from random import random
    
    def shuffle_with_freeze(x):
        for i in reversed(xrange(1, len(x))):
            if x[i].freeze: continue # fixed
            # pick an element in x[:i+1] with which to exchange x[i]
            j = int(random() * (i+1))
            if x[j].freeze: continue #NOTE: it might make it less random
            x[i], x[j] = x[j], x[i] # swap
    

提交回复
热议问题