Minimum number of deletions and insertions to transform one string into another | Returns length of length common subsequence for str1 [ 0. . m - 1 ] , str2 [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of str1 [ 0. . i - 1 ] and str2 [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; function to find minimum number of deletions and insertions ; Driver Code ; Function Call
def lcs ( str1 , str2 , m , n ) : NEW_LINE INDENT L = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( str1 [ i - 1 ] == str2 [ j - 1 ] ) : NEW_LINE INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ m ] [ n ] NEW_LINE DEDENT def printMinDelAndInsert ( str1 , str2 ) : NEW_LINE INDENT m = len ( str1 ) NEW_LINE n = len ( str2 ) NEW_LINE leng = lcs ( str1 , str2 , m , n ) NEW_LINE print ( " Minimum ▁ number ▁ of ▁ deletions ▁ = ▁ " , m - leng , sep = ' ▁ ' ) NEW_LINE print ( " Minimum ▁ number ▁ of ▁ insertions ▁ = ▁ " , n - leng , sep = ' ▁ ' ) NEW_LINE DEDENT str1 = " heap " NEW_LINE str2 = " pea " NEW_LINE printMinDelAndInsert ( str1 , str2 ) NEW_LINE