Guest User

Untitled

a guest
Jun 20th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. def nw(a, b):
  2. """ Returns Levenstein distance of two strings using NW """
  3. a = ' ' + a
  4. b = ' ' + b
  5. class matrix(list):
  6. """ A cute little matrix object """
  7. def __init__(self, x, y):
  8. """ initialize """
  9. [ self.append([0]*x) for i in range(y) ]
  10.  
  11. def __repr__(self):
  12. """ niceprint """
  13. return '\n'.join([' '.join([str(j) for j in i]) for i in self ])
  14.  
  15. m = matrix(len(a), len(b))
  16.  
  17. for f, y in zip(b, range(len(m))):
  18. for s, x in zip(a, range(len(m[y]))):
  19. if y is 0 and x is 0:
  20. continue
  21. elif y == 0:
  22. m[y][x] = m[y][x-1] + 1
  23. elif x == 0:
  24. m[y][x] = m[y-1][x] + 1
  25. elif f == s:
  26. m[y][x] = m[y-1][x-1]
  27. elif f != s:
  28. m[y][x] = min([m[y-1][x-1]+1, m[y-1][x]+1, m[y][x-1]+1])
  29.  
  30. print m
  31.  
  32. print '%s from %s = %s' % (a[1:], b[1:], m[-1][-1])
Add Comment
Please, Sign In to add comment