Smallest Derangement of Sequence | Efficient Python3 program to find smallest derangement . ; Generate Sequence S ; Generate Derangement ; Only if i is odd Swap S [ N - 1 ] and S [ N ] ; Print Derangement ; Driver Code
def generate_derangement ( N ) : NEW_LINE INDENT S = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT S [ i ] = i NEW_LINE DEDENT D = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 , 2 ) : NEW_LINE INDENT if i == N : NEW_LINE INDENT D [ N ] = S [ N - 1 ] NEW_LINE D [ N - 1 ] = S [ N ] NEW_LINE DEDENT else : NEW_LINE INDENT D [ i ] = i + 1 NEW_LINE D [ i + 1 ] = i NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( D [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT generate_derangement ( 10 ) NEW_LINE DEDENT