Sub topic 1
Turning One String into Another: The Three Edit Operations
Spell checkers suggest "receive" when you type "recieve". Version control tools show which lines changed between two files. Biologists line up DNA sequences that differ by a few mutations. Each of these tasks asks the same question: how few small changes does it take to turn one sequence into another?
To answer it, we first need to decide what counts as a change. This chapter defines the three edit operations that edit distance is built on. It shows how to apply them to a string in code and explains the details that cause bugs later: positions that shift, the order of edits, and how edits can be undone.
Prerequisites
This chapter assumes you are comfortable with the following:
- Basic Python: functions, loops, tuples, and lists.
- Strings as sequences of characters, with zero-based indexing.
- Big-O notation, used here only in passing.
Later chapters also use recursion and dynamic programming. You do not need them for this one.
The Three Operations
A string is a finite sequence of characters drawn from some alphabet. The alphabet might be letters, bytes, DNA bases (A, C, G, T), or whole lines of a file. Edit distance works the same way for any of them.
Classic edit distance allows three operations, each acting on a single character:
| Operation | Effect | Example | Length change |
|---|---|---|---|
| Insertion | Add one character at some position | `cat` → `cart` | +1 |
| Deletion | Remove one character | `cart` → `cat` | −1 |
| Substitution | Replace one character with a different one | `cat` → `cut` | 0 |
Two points are easy to miss.
First, a substitution must change the character. Replacing a with a is not an edit. When the characters at aligned positions already agree, we call that a match, and it costs nothing.
Second, swapping two neighboring characters (ab → ba) is not one of the three operations. With only these three, a swap takes two edits, such as two substitutions. A later chapter adds transposition as a fourth operation and explains why doing so is harder than it looks.
A Worked Example: kitten to sitting
The standard example turns kitten into sitting. One way to do it takes three edits:
- Substitute
kwiths:kitten→sitten - Substitute
ewithi:sitten→sittin - Insert
gat the end:sittin→sitting
Many other sequences work too. You could delete all six letters of kitten and then insert all seven letters of sitting, which takes 13 edits. Edit distance asks for the shortest possible sequence. Here no sequence shorter than three exists. The next chapter defines this minimum precisely, and later chapters show how to compute it.
Applying Edits in Code
To reason about edits carefully, it helps to apply them mechanically. The function below represents each edit as a tuple (op, pos, old, new):
("ins", pos, "", new)insertsnewso that it ends up at indexpos.("del", pos, old, "")deletes the character atpos, which must equalold.("sub", pos, old, new)replacesoldatposwithnew.
Storing old for deletions and substitutions looks redundant, but it catches mistakes, and it makes every edit reversible, as you will see below.
def apply_edits(s, edits):
"""Apply a list of (op, pos, old, new) edits to s, in order.
Each position refers to the string as it is when that edit runs.
"""
chars = list(s)
for op, pos, old, new in edits:
if op == "ins":
if not 0 <= pos <= len(chars):
raise IndexError(f"insert position {pos} out of range")
if len(new) != 1:
raise ValueError("insert exactly one character")
chars.insert(pos, new)
elif op == "del":
if not 0 <= pos < len(chars) or chars[pos] != old:
raise ValueError(f"cannot delete {old!r} at {pos}")
del chars[pos]
elif op == "sub":
if not 0 <= pos < len(chars) or chars[pos] != old:
raise ValueError(f"cannot substitute {old!r} at {pos}")
if len(new) != 1 or new == old:
raise ValueError("substitute exactly one different character")
chars[pos] = new
else:
raise ValueError(f"unknown operation {op!r}")
return "".join(chars)
script = [
("sub", 0, "k", "s"),
("sub", 4, "e", "i"),
("ins", 6, "", "g"),
]
assert apply_edits("kitten", script) == "sitting"
print("kitten ->", apply_edits("kitten", script))An insert position can equal len(chars), which means appending at the end. Deletions and substitutions need an existing character, so their position must be strictly less than the length.
Positions Shift as You Edit
Every insertion or deletion moves the characters after it. In the script above, the final g goes in at index 6 because sittin has six characters at that point. Measured against the original kitten, the same spot would also be index 6, but only because no earlier edit changed the length.
When earlier edits do change the length, the same position numbers can produce different results depending on order:
# Delete index 0, then index 1 of what remains.
assert apply_edits("abc", [("del", 0, "a", ""), ("del", 1, "c", "")]) == "b"
# Delete index 1 first, then index 0.
assert apply_edits("abc", [("del", 1, "b", ""), ("del", 0, "a", "")]) == "c"
print("order changes the result")Alignments: A Position-Free View
You can also describe an edit sequence by writing the two strings one above the other, with a gap symbol - where a character has no partner. This picture is called an alignment:
| Column | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| kitten | k | i | t | t | e | n | - |
| sitting | s | i | t | t | i | n | g |
| Kind | sub | match | match | match | sub | match | ins |
Each column is one of four kinds:
- Both characters are equal: a match, which costs nothing.
- Both characters differ: a substitution.
- The top character is over a gap: a deletion.
- A gap is over the bottom character: an insertion.
A column with a gap above a gap is not allowed.
Alignments avoid the shifting-position problem completely, because each column pairs characters from the two original strings. They also match how the dynamic programming algorithm in later chapters works: it builds an alignment from left to right, one column at a time.
Edits Can Be Undone
Insertion and deletion undo each other, and a substitution is undone by substituting back. So if a script turns a into b, you can turn b back into a by reversing the list and inverting each edit:
def invert(edits):
inverse = []
for op, pos, old, new in reversed(edits):
if op == "ins":
inverse.append(("del", pos, new, ""))
elif op == "del":
inverse.append(("ins", pos, "", old))
else:
inverse.append(("sub", pos, new, old))
return inverse
script = [("sub", 0, "k", "s"), ("sub", 4, "e", "i"), ("ins", 6, "", "g")]
assert apply_edits("sitting", invert(script)) == "kitten"
print("sitting ->", apply_edits("sitting", invert(script)))The inverse has the same number of edits. So the fewest edits from a to b always equals the fewest edits from b to a. This symmetry is one of the properties that makes edit distance a true metric, which a later chapter covers.
Quick Bounds Before Any Algorithm
You can bound the answer for strings of lengths m and n without computing anything:
- Lower bound, |m − n|. Each edit changes the length by at most one, so you need at least that many edits to fix the length difference.
- Upper bound, max(m, n). Line the strings up position by position, substitute wherever they differ in the first min(m, n) positions, then insert or delete the remaining |m − n| characters.
For kitten (6) and sitting (7), the answer must lie between 1 and 7. The true value, 3, falls in that range. These bounds are cheap sanity checks for any implementation you write, and the lower bound helps you skip work in threshold-bounded search.
Summary of Common Errors
- Treating a same-character "substitution" as an edit.
- Counting an adjacent swap as one edit when only the three basic operations are allowed.
- Mixing original-string and current-string positions in an edit script.
- Forgetting that an insertion position can equal the string length.
Exercise
Write an edit script in the (op, pos, old, new) format, with positions referring to the current string, that turns "flaw" into "lawn" using exactly two edits. Then give the lower and upper bounds from this chapter for these two strings.
Show answer
[("del", 0, "f", ""), ("ins", 3, "", "n")]. Deleting "f" gives "law", and inserting "n" at index 3 gives "lawn". Both strings have length 4, so the lower bound is |4 − 4| = 0 and the upper bound is max(4, 4) = 4. (Four substitutions would also work, but two edits is the minimum.)
Exercise
The script [("ins", 0, "", "x"), ("del", 1, "a", "")] is applied to "ab". What is the result, and what does invert() return for it?
Show answer
Inserting "x" at 0 gives "xab". Deleting index 1 removes "a" and gives "xb". The inverse is [("ins", 1, "", "a"), ("del", 0, "x", "")]. Applied to "xb", it gives "xab" and then "ab".
Exercise
Using only insertion, deletion, and substitution, what is the fewest number of edits that turns "ab" into "ba"? Explain why it cannot be one.
Show answer
Two, for example two substitutions (a→b, then b→a), or deleting "a" and then appending "a". It cannot be one: the lengths are equal, so a single insertion or deletion would leave the wrong length, and a single substitution changes only one position, while both positions differ.