Fixed bug (and added test) in distance.

This commit is contained in:
Jeremy Fincher 2003-04-06 15:10:14 +00:00
parent 1b79a300f9
commit 16374c53d6
2 changed files with 10 additions and 7 deletions

View File

@ -161,17 +161,18 @@ def distance(s, t):
return m return m
elif m == 0: elif m == 0:
return n return n
d = range(n+1) d = []
for i in range(len(d)): for i in range(n+1):
d[i] = range(m+1) d.append([])
for j in range(m+1):
d[i].append(0)
d[0][j] = j
d[i][0] = i
for i in range(1, n+1): for i in range(1, n+1):
cs = s[i-1] cs = s[i-1]
for j in range(1, m+1): for j in range(1, m+1):
ct = t[j-1] ct = t[j-1]
if cs == ct: cost = int(cs != ct)
cost = 0
else:
cost = 1
d[i][j] = min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+cost) d[i][j] = min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+cost)
return d[n][m] return d[n][m]

View File

@ -62,6 +62,8 @@ class UtilsTest(unittest.TestCase):
self.assertEqual(utils.distance('a', 'ab'), 1) self.assertEqual(utils.distance('a', 'ab'), 1)
self.assertEqual(utils.distance('foo', ''), 3) self.assertEqual(utils.distance('foo', ''), 3)
self.assertEqual(utils.distance('', 'foo'), 3) self.assertEqual(utils.distance('', 'foo'), 3)
self.assertEqual(utils.distance('appel', 'nappe'), 2)
self.assertEqual(utils.distance('nappe', 'appel'), 2)
def testAbbrev(self): def testAbbrev(self):
L = ['abc', 'bcd', 'bbe', 'foo', 'fool'] L = ['abc', 'bcd', 'bbe', 'foo', 'fool']