23/40
Part 5 of 7 · The answer and a limitLearn and do

Walk back through the table, or keep a parent for each cell

A table holds scores. When the question asks for the edits, the subsequence or the route, there are two ways to get it.

Walk back through the table. Start at the cell that holds the answer, and ask which neighbor explains its value. The booksite describes it for the longest common subsequence: retrace the steps of the algorithm backward, and rediscover the path of choices. For edit distance:

  • a cell equal to its diagonal, with matching letters, was a keep
  • a cell one more than its diagonal was a swap
  • one more than the cell above was a delete
  • one more than the cell to the left was an insert
def edit_script(a, b):
    d = edit_distance(a, b)
    i, j, ops = len(a), len(b), []
    while i > 0 or j > 0:
        if i > 0 and j > 0 and a[i - 1] == b[j - 1] and d[i][j] == d[i - 1][j - 1]:
            ops.append(f"keep {a[i - 1]}")
            i, j = i - 1, j - 1
        elif i > 0 and j > 0 and d[i][j] == d[i - 1][j - 1] + 1:
            ops.append(f"swap {a[i - 1]} for {b[j - 1]}")
            i, j = i - 1, j - 1
        elif i > 0 and d[i][j] == d[i - 1][j] + 1:
            ops.append(f"delete {a[i - 1]}")
            i -= 1
        else:
            ops.append(f"insert {b[j - 1]}")
            j -= 1
    return ops[::-1]


print(edit_script("tails", "train"))
Predict

The walk back starts at the corner of the tails and train table. Which edit is the last one in the script?

Pick one to see what it prints.
Pick an answer above to see the rest