Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Edit Distance

Hard · 90 XP

Compute Levenshtein distance: the fewest single-character insertions, deletions or substitutions turning one word into another. Print it for four pairs.

Target output
'kitten' -> 'sitting': 3
'flaw' -> 'lawn': 2
'abc' -> 'abc': 0
'' -> 'hello': 5
Blank · autosaved
PYword-ladder-cost.py
Run your code to check it…
Guide

How to approach Edit Distance

Edit distance looks for the cheapest way to turn one word into another, and comparing letters one position at a time does not work: a single insertion shifts everything after it. Instead, build up answers for every prefix of both words.

Let cell (i, j) hold the distance between the first i letters of a and the first j letters of b. If those last letters match, the cell copies its diagonal neighbour. If not, it is 1 plus the cheapest of deleting (the cell above), inserting (the cell to the left) or substituting (the diagonal). The first row and column are 0, 1, 2 and so on, because turning a prefix into an empty string costs one deletion per letter.

Worked through on this data

  1. kitten → sitting costs 3: substitute k for s, substitute e for i, insert g at the end.
  2. flaw → lawn costs 2: delete the f to get law, then insert n to get lawn.
  3. abc → abc costs 0, and the empty string → hello costs 5, one insertion per letter: exactly the first row of the table.

Common mistakes

  • Comparing letters position by position: "flaw" and "lawn" differ in all four positions, yet the true distance is 2.
  • Initialising the first row and column to zeros instead of 0, 1, 2, …, which makes every distance too small.
  • Mixing up which neighbour means insert and which means delete. Both cost 1, so the answer comes out right, but reconstructing the actual edits goes wrong.

Time and space

The table has (m + 1) × (n + 1) cells, each filled in constant time: O(m · n) time. Keeping only the previous row, as the solution does, cuts space to O(n).

Where this shows up

Spell checkers suggest the dictionary words with the smallest edit distance, fuzzy search tolerates typos the same way, and bioinformatics aligns DNA sequences with weighted versions of this table.

Take it further

Keep the full table and walk it backwards from the bottom-right cell to print the actual edits, such as "substitute k with s".

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path