Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def levenshtein(a, b, mem={}):
- """ calculates the Levenshtein distance between two strings, a and b.
- PARAMETERS:
- a: str
- b: str
- RETURNS:
- integer distance between two strings
- EXAMPLE:
- > levenshtein('hello world', 'howdy world')
- 4
- """
- try:
- assert isinstance(a, str) and isinstance(b, str)
- except AssertionError as e:
- print(e)
- sys.exit(2)
- ij = (len(a), len(b))
- if min(ij) == 0:
- mem[ij] = max(ij)
- elif ij not in mem:
- cost = a[-1] != b[-1]
- mem[ij] = min(levenshtein(a[0:-1], b, mem) + 1,
- levenshtein(a, b[0:-1], mem) + 1,
- levenshtein(a[0:-1], b[0:-1], mem) + cost)
- return mem[ij]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement