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

Added matching with substitutions.

parent 60d82dc3
def _hamming(path, node, word, distance):
"""
:arg str path: Path taken so far to reach the current node.
:arg dict node: Current node.
:arg str word: Query word.
:arg int distance: Amount of errors we can still make.
:returns str:
"""
if distance < 0:
return ''
if not word:
if '' in node:
return path
return ''
car, cdr = word[0], word[1:]
for char in node:
result = _hamming(
path + char, node[char], cdr, distance - int(char != car))
if result:
return result
return ''
class Trie(object): class Trie(object):
def __init__(self, words): def __init__(self, words):
""" """
...@@ -55,3 +81,6 @@ class Trie(object): ...@@ -55,3 +81,6 @@ class Trie(object):
def has_prefix(self, word): def has_prefix(self, word):
return self._find(word) != {} return self._find(word) != {}
def hamming(self, word, distance):
return _hamming('', self.root, word, distance)
...@@ -53,3 +53,48 @@ class TestTrie(object): ...@@ -53,3 +53,48 @@ class TestTrie(object):
def test_prefix_order(self): def test_prefix_order(self):
assert Trie(['test', 'te']).root == Trie(['te', 'test']).root assert Trie(['test', 'te']).root == Trie(['te', 'test']).root
def test_hamming_0_no_prefix(self):
assert self._trie.hamming('ab', 0) == ''
def test_hamming_0_match(self):
assert self._trie.hamming('abc', 0) == 'abc'
def test_hamming_0_match_sub(self):
assert self._trie.hamming('te', 0) == 'te'
def test_hamming_0_too_long(self):
assert self._trie.hamming('abcd', 0) == ''
def test_hamming_1_match(self):
assert self._trie.hamming('abc', 1) == 'abc'
def test_hamming_1_match_sub(self):
assert self._trie.hamming('te', 1) == 'te'
def test_hamming_1_match_1(self):
assert self._trie.hamming('xbc', 1) == 'abc'
def test_hamming_1_match_2(self):
assert self._trie.hamming('axc', 1) == 'abc'
def test_hamming_1_match_3(self):
assert self._trie.hamming('abx', 1) == 'abc'
def test_hamming_1_no_prefix(self):
assert self._trie.hamming('ab', 1) == ''
def test_hamming_1_too_long(self):
assert self._trie.hamming('abcd', 1) == ''
def test_hamming_1_match_sub_1(self):
assert self._trie.hamming('tx', 1) == 'te'
def test_hamming_1_match_sub_2(self):
assert self._trie.hamming('xe', 1) == 'te'
def test_hamming_1_mismatch(self):
assert self._trie.hamming('txxt', 1) == ''
def test_hamming_2_match(self):
assert self._trie.hamming('txxt', 2) == 'test'
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