Sub topic 9
Custom Costs for Each Operation
This chapter assumes you already know the Levenshtein recurrence, how to fill the dynamic programming table, and how traceback recovers an edit script. All three come from earlier chapters. Here we keep the same table and the same three neighbors. The only change is that each step can now cost a different amount.
Why Unit Costs Are Not Always Right
Plain Levenshtein distance charges 1 for every insertion, deletion, and substitution. That keeps the model simple, but it treats every mistake as equally likely. Real errors are not like that:
- A typist who presses
gwhen they meanthhit a neighboring key. Swapping inpforhwould be a much less likely slip. - In DNA, some point mutations are much more common than others.
- An OCR engine often confuses
0withObut rarely confuses0withW.
If you want "distance" to track "how likely is this corruption," the cost of each operation has to depend on the characters it touches.
The Generalized Recurrence
Replace the constant 1 with three cost functions:
del(x)is the cost of deleting characterxfrom the source.ins(y)is the cost of inserting characteryinto the target.sub(x, y)is the cost of replacingxwithy. We requiresub(x, x) = 0.
The recurrence for D[i][j], the cheapest way to turn the first i characters of a into the first j characters of b, becomes:
D[0][0] = 0D[i][0] = D[i-1][0] + del(a[i])D[0][j] = D[0][j-1] + ins(b[j])D[i][j] = min(D[i-1][j] + del(a[i]), D[i][j-1] + ins(b[j]), D[i-1][j-1] + sub(a[i], b[j]))
The base cases change too. With unit costs, the first column is just 0, 1, 2, .... With weights, the first column holds running sums of deletion costs and the first row holds running sums of insertion costs. A common bug is to keep dp[i][0] = i while switching to weighted costs. That gives wrong answers whenever deletions do not cost exactly 1.
The correctness argument from the unit-cost case still holds. Any edit script ends with one of the three operations on the last characters. Removing that last operation leaves an optimal script for a smaller pair of prefixes. Nothing in that argument needs the costs to be equal. It only needs them to be non-negative, which the next sections explain.
Implementation
The function below takes the costs as callables, so one implementation covers every scheme in this chapter.
def weighted_edit_distance(a, b, ins_cost, del_cost, sub_cost):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
dp[i][0] = dp[i - 1][0] + del_cost(a[i - 1])
for j in range(1, n + 1):
dp[0][j] = dp[0][j - 1] + ins_cost(b[j - 1])
for i in range(1, m + 1):
for j in range(1, n + 1):
ca, cb = a[i - 1], b[j - 1]
sub = 0 if ca == cb else sub_cost(ca, cb)
dp[i][j] = min(
dp[i - 1][j] + del_cost(ca), # delete ca
dp[i][j - 1] + ins_cost(cb), # insert cb
dp[i - 1][j - 1] + sub, # match or substitute
)
return dp[m][n]
one = lambda c: 1
unit_sub = lambda x, y: 1
two_sub = lambda x, y: 2
# Unit costs reproduce ordinary Levenshtein distance.
assert weighted_edit_distance("kitten", "sitting", one, one, unit_sub) == 3
# Substitution priced at 2 (= one delete + one insert).
assert weighted_edit_distance("kitten", "sitting", one, one, two_sub) == 5
# Asymmetric costs: inserting is cheap, deleting is expensive.
cheap_ins = lambda c: 1
dear_del = lambda c: 3
assert weighted_edit_distance("ab", "abc", cheap_ins, dear_del, unit_sub) == 1
assert weighted_edit_distance("abc", "ab", cheap_ins, dear_del, unit_sub) == 3
print("all checks passed")The loop still does constant work per cell, as long as each cost function runs in constant time. A lookup in a dictionary or a small matrix does. Time stays O(mn), and the two-row space trick from the previous chapter carries over unchanged.
A Worked Example: Keyboard-Aware Spelling Correction
Suppose a user types gello. Plain Levenshtein puts hello, jello, and cello all at distance 1, so it cannot rank them. Now make substitutions between neighboring keys cheaper. The adjacency rule below treats keys within one row and one column of each other as neighbors. That is a rough model of a QWERTY layout, which ignores how the rows are staggered.
ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
POS = {c: (r, col) for r, row in enumerate(ROWS) for col, c in enumerate(row)}
def keyboard_sub(x, y):
if x in POS and y in POS:
(r1, c1), (r2, c2) = POS[x], POS[y]
if abs(r1 - r2) <= 1 and abs(c1 - c2) <= 1:
return 1 # neighboring key: likely slip
return 2 # anything else
indel = lambda c: 2
def weighted_edit_distance(a, b, ins_cost, del_cost, sub_cost):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
dp[i][0] = dp[i - 1][0] + del_cost(a[i - 1])
for j in range(1, n + 1):
dp[0][j] = dp[0][j - 1] + ins_cost(b[j - 1])
for i in range(1, m + 1):
for j in range(1, n + 1):
ca, cb = a[i - 1], b[j - 1]
sub = 0 if ca == cb else sub_cost(ca, cb)
dp[i][j] = min(dp[i - 1][j] + del_cost(ca),
dp[i][j - 1] + ins_cost(cb),
dp[i - 1][j - 1] + sub)
return dp[m][n]
typed = "gello"
for word in ["hello", "jello", "cello"]:
print(word, weighted_edit_distance(typed, word, indel, indel, keyboard_sub))
# hello 1
# jello 2
# cello 2g and h sit next to each other, so hello now wins. The costs here are integers on purpose, for a reason explained under traceback below.
Common Cost Schemes
| Domain | Insertion / deletion | Substitution | Rationale |
|---|---|---|---|
| Plain Levenshtein | 1 / 1 | 1 | Every error equally likely |
| Indel-style | 1 / 1 | 2 (or ≥ 2) | Substitution never beats delete plus insert |
| Keyboard typos | 2 / 2 | 1 for neighboring keys, 2 otherwise | Neighboring-key slips are common |
| DNA | 3 / 3 | 1 for transitions (A↔G, C↔T), 2 for transversions | Transitions mutate more often |
| Data entry with dropped keys | 1 / 3 | 1 | Missing characters are more likely than extra ones |
Rules Your Costs Should Follow
Costs must be non-negative
The optimal-substructure argument assumes that adding an operation never makes a script cheaper. A negative cost breaks that assumption. With a negative insertion cost, for example, inserting and then deleting the same character over and over could drive the total down forever. The DP would return a number, but that number would not be a minimum over all scripts. Keep every cost at zero or above. Use zero only for matching identical characters, unless you really mean for two distinct characters to count as the same.
Substitution above insertion plus deletion is dead weight
If sub(x, y) > del(x) + ins(y), the DP will never choose that substitution, because deleting x and inserting y is always cheaper. The second assertion in the first code block shows the borderline case. With substitution at 2 and indels at 1, kitten to sitting costs 5, the same as a distance that only allows insertions and deletions. The next chapter shows that this indel-only distance equals m + n - 2·LCS(a, b), where LCS is the longest common subsequence.
A related check: if sub(x, z) > sub(x, y) + sub(y, z), the DP still cannot route through y, because each cell substitutes exactly once. The cost table you supply may then overstate how far apart x and z really are. If you build costs from probabilities, such as -log P(error), make sure the table obeys the triangle inequality, or accept that its values will be used as given.
Asymmetric costs make the distance direction-dependent
When ins differs from del, or sub(x, y) differs from sub(y, x), you get d(a, b) ≠ d(b, a). The asserts above show this: ab → abc costs 1, while abc → ab costs 3. This is often what you want, because "typed string to dictionary word" is a direction. But it means the result is no longer a symmetric distance, so data structures that assume symmetry, such as BK-trees, can give wrong answers. A later chapter on metric properties covers exactly when a weighted distance is still a metric.
Traceback with Weights
Traceback works as before. At each cell, step to a neighbor whose value plus the edge cost equals the current value. Two details change:
- You must recompute the edge cost with the same functions you used to fill the table. The unit-cost test
dp[i][j] == dp[i-1][j] + 1silently picks the wrong predecessor, or none at all. - With floating-point costs such as 0.3 or
-log p, an exact equality test can fail because of rounding. When that happens, traceback picks no predecessor or the wrong one. You can scale costs to integers, usefractions.Fraction, or compare withmath.isclose. A sturdier option is to record which choice won in a separate table while filling the main one, then follow those recorded pointers.
Exercises
Exercise
With ins = del = 1 and sub = 3 for any two different characters, what is the distance from "kitten" to "sitting"? Explain without filling the table.
Show answer
5. A substitution at cost 3 always loses to a delete plus an insert at cost 2, so the DP behaves like indel-only distance: m + n - 2·LCS = 6 + 7 - 2·4 = 5. The longest common subsequence here is "ittn".
Exercise
Using the DNA scheme from the table (indel 3, transition 1, transversion 2), compute d("ACGT", "GCGT") and d("ACGT", "CCGT").
Show answer
d("ACGT", "GCGT") = 1, because A→G is a transition. d("ACGT", "CCGT") = 2, because A→C is a transversion. Doing the change with a delete plus an insert would cost 6, so a single substitution is optimal in both cases.
Exercise
A colleague fills the weighted table correctly but keeps the base cases dp[i][0] = i and dp[0][j] = j, with deletion cost 3. What goes wrong for a = "abc", b = ""?
Show answer
The function returns 3 when the true cost is 9. The first column must hold running sums of deletion costs (3, 6, 9), and the wrong base case also feeds lower costs into every interior cell that depends on that column.