Derangement

A derangement is a permutation of the elements of a set, such that no element appears in its original position.

In other words, derangement is a permutation that has no fixed points.

Implementation

 def derange(lst):
     idx = range(len(lst))
     nidx = range(len(lst))
     while(True):
             random.shuffle(nidx)
             if(any([a==b for (a,b) in zip(idx,nidx)])):
                     continue
             else:
                     res =[]
                     for i in nidx:
                             res.append(lst[i])
                     return res
 def derange(lst):
...     idx =range(len(lst))
...     nidx = []
...     for i in range(len(lst)):
...             flag= i in idx
...             if(flag):
...                     idx.remove(i)
...             j=random.choice(idx)
...             idx.remove(j)
...             nidx.append(j)
...             if(flag):
...                     idx.append(i)
...     res = []
...     for i in nidx:
...             res.append(lst[i])
...     return res

results matching ""

    No results matching ""