I have encountered the edit distance (Levenshtein distance) problem. I have looked at other similar stackoverflow questions, and is certain that my question is distinct from them - either from the language used or the approach.
I have used a 2D array that compares the two strings, and dynamic programming to store previous values. If i and j in the string indices match, it would output 0, as we don't need to do anything; else, the output is 1. It is as shown in the picture below, the orange arrow represents a match.
(Code below is edited after suggestions from answers)
def edit_distance(source, target):
n = len(target)+1
m = len(source)+1
# let D denote the 2-dimensional array, m is the column, n is row
D = [ [0]*m for _ in range(n)]
# the loop inside is the target string, we operate this
# while the loop outside is the source string
for j in range(0, m):
for i in range(0, n):
if target[i-1] == source[j-1]:
# match, insertion and deletion, find the path with least move
D[i][j] = min(D[i-1][j-1], D[i-1][j]+1, D[i][j-1]+1)
else:
# mismatch, insertion and deletion, find the path with least move
D[i][j] = min(D[i-1][j-1]+1, D[i-1][j]+1, D[i][j-1]+1)
return D[n-1][m-1]
print(edit_distance("distance", "editing"))
However, the final output was 8 in my code, while the optimal editing distance between the strings "editing" and "distance" should be 5, and I am very confused. Could you please help with it from the approach of dynamic programming?