def generate_derangements(perm):
 p = multiset_permutations(perm)
 indices = range(len(perm))
 p0 = next(p)
 for pi in p:
  if all(((pi[i] != p0[i]) for i in indices)):
   (yield pi)

def generate_derangements ( perm ) : p = multiset_permutations ( perm ) indices = range ( len ( perm ) ) p0 = next ( p ) for pi in p : if all ( ( ( pi [ i ] != p0 [ i ] ) for i in indices ) ) : ( yield pi )
routine to generate unique derangements .