32/40
Part 7 of 7 · Follow-upsLearn and do

Less memory? Often two rows will do, and the walk back is the price

Each row of the edit distance table reads only the row above it, so keep two rows and swap them:

def edit_distance_two_rows(a, b):
    prev = list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j - 1], prev[j], cur[j - 1])
        prev = cur
    return prev[-1]


print(edit_distance_two_rows("tails", "train"))
3

The same answer from two rows. Here is what the function holds while it fills the last row:

The full table, and the two rows left while row s is filled
full
""train""012345t101234a211123i322212l433322s544433
two rows
""trainl433322s544433

The walk back needs the rows that are gone: it runs from the corner up to row "".

Predict

At 2,000 letters each, the full table peaked at 118 MiB. About how much do two rows take?

Pick an answer above to see the rest