Measures the amount of difference between two strings. The return value is the number of operations (insert, delete, replace) required to transform string a into string b.
(string1, string2)
| 247 | #--- STRING SIMILARITY ----------------------------------------------------------------------------- |
| 248 | |
| 249 | def levenshtein(string1, string2): |
| 250 | """ Measures the amount of difference between two strings. |
| 251 | The return value is the number of operations (insert, delete, replace) |
| 252 | required to transform string a into string b. |
| 253 | """ |
| 254 | # http://hetland.org/coding/python/levenshtein.py |
| 255 | n, m = len(string1), len(string2) |
| 256 | if n > m: |
| 257 | # Make sure n <= m to use O(min(n,m)) space. |
| 258 | string1, string2, n, m = string2, string1, m, n |
| 259 | current = range(n+1) |
| 260 | for i in range(1, m+1): |
| 261 | previous, current = current, [i]+[0]*n |
| 262 | for j in range(1, n+1): |
| 263 | insert, delete, replace = previous[j]+1, current[j-1]+1, previous[j-1] |
| 264 | if string1[j-1] != string2[i-1]: |
| 265 | replace += 1 |
| 266 | current[j] = min(insert, delete, replace) |
| 267 | return current[n] |
| 268 | |
| 269 | edit_distance = levenshtein |
| 270 |
no test coverage detected
searching dependent graphs…