defedit_distance(A,B):"""Calculate the edit distance (levenshtein) between strings A and B. Also, generate the longest common subsequence from the resulting matrix after edit distance has been calculated."""# first, create an empty matrix. Note, we only care about populating the# first row and first column with the proper values. All other cells will# have their default values replacedM=[[i+jforjinrange(0,len(A)+1)]foriinrange(0,len(B)+1)]# now, go row by row and calculate the edit distancecolumn_range=range(1,len(A)+1)# each rowforiinrange(1,len(B)+1):# each columnforjincolumn_range:cost=int(B[i-1]isA[j-1])^1M[i][j]=min(M[i-1][j]+1,M[i][j-1]+1,M[i-1][j-1]+cost)print"edit distance:",M[i][j]# print out the matrix in a nice wayprintprint"edit distance matrix:"forrowinM:printrowprint# now, build the longest common subsequence from the resulting matrixsub=""while(i>0)and(j>0):# characters match, move diagonally (left and up)ifB[i-1]isA[j-1]:i=i-1j=j-1sub=B[i]+sub# characters don't match, lets go to the cell with the smallest# edit distanceelse:# move up?ifM[i-1][j]<M[i][j-1]:i=i-1# move leftelse:j=j-1print"longest common subsequence:",subif__name__=="__main__":edit_distance("abcdef","xzceejf")