Reduce Hamming distance by swapping two characters | Python 3 code to decrease hamming distance using swap . ; Function to return the swapped indexes to get minimum hamming distance . ; Find the initial hamming distance ; Case - I : To decrease distance by two ; ASCII values of present character . ; If two same letters appear in different positions print their indexes ; Store the index of letters which is in wrong position ; Case : II ; If misplaced letter is found , print its original index and its new index ; Store the index of letters in wrong position ; Case - III ; Driver code
MAX = 26 NEW_LINE def Swap ( s , t , n ) : NEW_LINE INDENT dp = [ [ - 1 for x in range ( MAX ) ] for y in range ( MAX ) ] NEW_LINE tot = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] != t [ i ] ) : NEW_LINE INDENT tot += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT a = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE b = ord ( t [ i ] ) - ord ( ' a ' ) NEW_LINE if ( a == b ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( dp [ a ] [ b ] != - 1 ) : NEW_LINE INDENT print ( i + 1 , " ▁ " , dp [ a ] [ b ] + 1 ) NEW_LINE return NEW_LINE DEDENT dp [ b ] [ a ] = i NEW_LINE DEDENT A = [ - 1 ] * MAX NEW_LINE B = [ - 1 ] * MAX NEW_LINE for i in range ( n ) : NEW_LINE INDENT a = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE b = ord ( t [ i ] ) - ord ( ' a ' ) NEW_LINE if ( a == b ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( A [ b ] != - 1 ) : NEW_LINE INDENT print ( i + 1 , A [ b ] + 1 ) NEW_LINE return NEW_LINE DEDENT if ( B [ a ] != - 1 ) : NEW_LINE INDENT print ( i + 1 , B [ a ] + 1 ) NEW_LINE return NEW_LINE DEDENT A [ a ] = i NEW_LINE B [ b ] = i NEW_LINE DEDENT print ( " - 1" ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " permanent " NEW_LINE T = " pergament " NEW_LINE n = len ( S ) NEW_LINE if ( S == " " or T == " " ) : NEW_LINE INDENT print ( " Required ▁ string ▁ is ▁ empty . " ) NEW_LINE DEDENT else : NEW_LINE INDENT Swap ( S , T , n ) NEW_LINE DEDENT DEDENT