Predict the output
What does this print?
src, dst = "cat", "cut"
row = list(range(len(dst) + 1))
for i, a in enumerate(src, 1):
nxt = [i]
for j, b in enumerate(dst, 1):
if a == b:
nxt.append(row[j - 1])
else:
nxt.append(1 + min(row[j], nxt[j - 1], row[j - 1]))
row = nxt
print(row)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [3, 2, 2, 1]
Right: the last cell is 1, one replacement (a to u).
Keeping only one previous row gives the same answer as the full table while using memory for one row.
Why not the others?
- B [3, 2, 1, 1]. The 'cu' column against 'cat' costs 2.
- C [0, 1, 2, 3]. That is the first row before any letters of the source.
Steps come from running the Python solution.
Text version
horse to ros:
| Row | ∅ | r | o | s |
|---|---|---|---|---|
| ∅ | 0 | 1 | 2 | 3 |
| h | 1 | 1 | 2 | 3 |
| o | 2 | 2 | 1 | 2 |
| r | 3 | 2 | 2 | 2 |
| s | 4 | 3 | 3 | 2 |
| e | 5 | 4 | 4 | 3 |
Answer: 3 in cell (e, s), from (s, s).
cat to cut:
| Row | ∅ | c | u | t |
|---|---|---|---|---|
| ∅ | 0 | 1 | 2 | 3 |
| c | 1 | 0 | 1 | 2 |
| a | 2 | 1 | 1 | 2 |
| t | 3 | 2 | 2 | 1 |
Answer: 1 in cell (t, t), from (a, u).