Generate permutations with only adjacent swaps allowed | Python3 program to generate permutations with only one swap allowed . ; don 't swap the current position ; Swap with the next character and revert the changes . As explained above , swapping with previous is is not needed as it anyways happens for next character . ; Driver Code
def findPermutations ( string , index , n ) : NEW_LINE INDENT if index >= n or ( index + 1 ) >= n : NEW_LINE INDENT print ( ' ' . join ( string ) ) NEW_LINE return NEW_LINE DEDENT findPermutations ( string , index + 1 , n ) NEW_LINE string [ index ] , string [ index + 1 ] = string [ index + 1 ] , string [ index ] NEW_LINE findPermutations ( string , index + 2 , n ) NEW_LINE string [ index ] , string [ index + 1 ] = string [ index + 1 ] , string [ index ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = list ( "12345" ) NEW_LINE n = len ( string ) NEW_LINE findPermutations ( string , 0 , n ) NEW_LINE DEDENT