How similar are two words?
Make a typo in a name, and Ruby doesn't just complain: below the error message it suggests what you probably meant – lesson 28 showed it. Try it once more, the cell below goes wrong on purpose:
breakfast = "bacon"
puts breakfstA NameError, and below it: “Did you mean breakfast?” Ruby compared breakfst with every name it knows and picked the one that is most similar. But what does “similar” mean for a computer? It needs a number: how far apart are two words? The simplest measure works for words of the same length – count the places where they differ. That is the Hamming distance. zip lays the letters of both words side by side in pairs, and count counts the pairs that don't match:
def hamming(a, b)
a.chars.zip(b.chars).count { |x, y| x != y }
end
p hamming("toast", "roast")
p hamming("bacon", "bagel")
hamming("chunky", "chunky")Hamming has a weak spot, though. Leave out a single letter at the front, and every letter after it slides one place along – suddenly nothing matches any more. (Where one word has run out, zip pairs the letter with nil.)
p "chunky".chars.zip("hunky".chars)
hamming("chunky", "hunky")6, for one missing letter. What we want is the edit distance, named after Vladimir Levenshtein: the fewest edits that turn one word into the other, where an edit is inserting a letter, deleting one or replacing one. "hunky" becomes "chunky" with one insert, so their distance is 1. And this is how it is computed – look at the first letters. If they are equal, they cost nothing, and the distance is that of the rest. If not, try all three edits, each costing 1, and take the cheapest. When one word is empty, the distance is simply the length of the other. That is a recursion, as in lesson 30; a[1..] is a without its first letter:
def levenshtein(a, b)
return b.length if a.empty?
return a.length if b.empty?
return levenshtein(a[1..], b[1..]) if a[0] == b[0]
1 + [levenshtein(a[1..], b), # delete a's first letter
levenshtein(a, b[1..]), # insert b's first letter
levenshtein(a[1..], b[1..])].min # replace one by the other
end
p levenshtein("hunky", "chunky")
levenshtein("chunky", "funky")Right – but slow. Whenever the first letters differ, the method calls itself three times, and each of those calls may do the same again. Most of the calls ask questions that were answered long ago: for "chunky" and "funky" it makes 1387 calls to arrive at 2, and for "chunky bacon" and "funky beacon" it would be over 40 million – many seconds even outside the browser. The cure is the one fast_fib used in lesson 30: a hash as a memory. Whatever has been worked out once is looked up, never worked out again:
def levenshtein_memo(a, b, memo = {})
return b.length if a.empty?
return a.length if b.empty?
memo[[a, b]] ||=
if a[0] == b[0]
levenshtein_memo(a[1..], b[1..], memo)
else
1 + [levenshtein_memo(a[1..], b, memo),
levenshtein_memo(a, b[1..], memo),
levenshtein_memo(a[1..], b[1..], memo)].min
end
end
memo = {}
p levenshtein_memo("chunky bacon", "funky beacon", memo)
memo.size3 edits – delete the c, turn the h into an f, insert an e – and the memory holds just 142 answers instead of 40 million calls. Now turn the idea round: instead of asking from the top and remembering on the way, fill in all the small answers first, in an order where everything a step needs is already there – in a table. Row i, column j holds the distance between the first i letters of a and the first j letters of b. Row 0 counts 0, 1, 2 … (from nothing to j letters takes j inserts), and every row starts with its own number. Every other cell is the cheapest of three: the cell above plus 1, the cell to the left plus 1, or the cell diagonally above-left plus 0 or 1. That is called dynamic programming:
a = "chunky"
b = "funky"
table = [(0..b.length).to_a]
1.upto(a.length) do |i|
row = [i]
1.upto(b.length) do |j|
cost = a[i - 1] == b[j - 1] ? 0 : 1
above = table[i - 1][j] + 1 # delete
left = row[j - 1] + 1 # insert
diagonal = table[i - 1][j - 1] + cost # keep or replace
row << [above, left, diagonal].min
end
table << row
end
table.last.lastThe bottom-right corner is the answer, 2. Print the table with the letters along the edges, and you can see how it was built – row by row, each cell from its neighbours above and to the left:
puts " " + b.chars.join(" ")
table.each_with_index do |row, i|
letter = i == 0 ? " " : a[i - 1]
puts letter + " " + row.join(" ")
endFollow the diagonal: where two letters match (u and u, n and n …) the number is carried over for free. No recursion, no memory – two loops, and every cell is filled exactly once. For two words of 100 letters that is 10 000 little sums, done in a blink.
With a distance, “Did you mean?” takes one line: of all the words you know, take the one that is closest to the typo. min_by from lesson 13 does exactly that:
menu = %w[bacon egg toast coffee pancake]
p menu.min_by { |w| levenshtein_memo("bacn", w) }
menu.min_by { |w| levenshtein_memo("cofe", w) }Ruby's own “Did you mean?” works the same way, and you can use it yourself: DidYouMean::SpellChecker gets the dictionary, and correct returns the best candidates as an array. A word that is far from everything gets no suggestion at all – the checker has a limit, so that "xylophone" doesn't turn into "toast". (require "did_you_mean" makes sure it is loaded; on this page it already is.)
require "did_you_mean"
checker = DidYouMean::SpellChecker.new(dictionary: menu)
p checker.correct("bacn")
p checker.correct("panckae")
checker.correct("xylophone")The edit distance turns “similar” into a number. Spell checkers use it, search boxes that forgive typos, and biologists who compare DNA, whose letters are just A, C, G and T. A rule of thumb from this lesson goes far beyond words: the recursion is the easiest way to understand a problem; a memory or a table makes it fast.
suggest(word, words) returns the word from words that is closest to word – but only if it is at most 2 edits away; otherwise nil. So suggest("bacn", %w[bacon egg toast]) is "bacon", and "xylophone" gets nil. levenshtein_memo from above measures the distance.# def suggest(word, words)
# ... # the word from words with the smallest edit distance to word
# ... # - but nil when even that one is more than 2 edits away
# end
# p suggest("bacn", %w[bacon egg toast])
# p suggest("xylophone", %w[bacon egg toast])
"bcaon". For Levenshtein that costs 2 – two replacements. Write typo_distance(a, b), the edit distance in which swapping two neighbouring letters counts as just one edit: typo_distance("bcaon", "bacon") is 1. Build the table as above and give each cell a fourth candidate.# def typo_distance(a, b)
# ... # the table as above, row by row
# ... # plus: two neighbouring letters swapped cost just 1
# end
# typo_distance("bcaon", "bacon")