Commit 71025417 authored by Jeroen F.J. Laros's avatar Jeroen F.J. Laros

Added best match function.

parent bfa69990
...@@ -29,6 +29,10 @@ def _hamming(path, node, word, distance): ...@@ -29,6 +29,10 @@ def _hamming(path, node, word, distance):
return '' return ''
def _edit(path, node, word, distance):
pass
class Trie(object): class Trie(object):
def __init__(self, words): def __init__(self, words):
""" """
...@@ -89,3 +93,25 @@ class Trie(object): ...@@ -89,3 +93,25 @@ class Trie(object):
def hamming(self, word, distance): def hamming(self, word, distance):
return _hamming('', self.root, word, distance) return _hamming('', self.root, word, distance)
def best_hamming(self, word, distance):
"""
Find the best match with {word} in the trie.
:arg str word: Query word.
:arg int distance: Amount of errors we can still make.
:returns str: Best match with {word}.
"""
if word in self:
return word
for i in range(1, distance + 1):
result = self.hamming(word, i)
if result:
return result
return ''
def edit(self, word, distance):
return _edit('', self.root, word, distance)
...@@ -81,6 +81,9 @@ class TestTrie(object): ...@@ -81,6 +81,9 @@ class TestTrie(object):
def test_hamming_1_match_3(self): def test_hamming_1_match_3(self):
assert self._trie.hamming('abx', 1) == 'abc' assert self._trie.hamming('abx', 1) == 'abc'
def test_hamming_1_match_4(self):
assert self._trie.hamming('abd', 1) == 'abc'
def test_hamming_1_no_prefix(self): def test_hamming_1_no_prefix(self):
assert self._trie.hamming('ab', 1) == '' assert self._trie.hamming('ab', 1) == ''
...@@ -98,3 +101,6 @@ class TestTrie(object): ...@@ -98,3 +101,6 @@ class TestTrie(object):
def test_hamming_2_match(self): def test_hamming_2_match(self):
assert self._trie.hamming('txxt', 2) == 'test' assert self._trie.hamming('txxt', 2) == 'test'
def test_best_hamming_match(self):
assert self._trie.best_hamming('abd', 1) == 'abd'
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment