Пример #1
0
    def test_insert(self):
        t = Trie()
        t.insert('alexandru')
        t.insert('alexandra')

        expected = {'a': {'l': {'e': {'x': {'a': {'n': {'d': {'r': {'u': {END: None}, 'a': {END: None}}}}}}}}}}
        self.assertEqual(t.root, expected, 'should build the correct tree')
Пример #2
0
def test_search_match_with_different_case():
    root_node = Trie()
    root_node.insert("dimitar")

    expected = False
    output = root_node.search("DIMITAR")
    assert output == expected
Пример #3
0
def test_search_match_of_suffix():
    root_node = Trie()
    root_node.insert("TESTED")

    expected = True
    output = root_node.search("TEST")
    assert output == expected
Пример #4
0
def test_search_word_longer_than_match():
    root_node = Trie()
    root_node.insert("TEST")

    expected = False
    output = root_node.search("TESTED")
    assert output == expected
Пример #5
0
    def test_insert_with_a_key_value_pair(self):
        t = Trie()
        t.insert('alexandru', True)
        t.insert('alexandra', False)

        expected = {'a': {'l': {'e': {'x': {'a': {'n': {'d': {'r': {'u': {END: True}, 'a': {END: False}}}}}}}}}}
        self.assertEqual(t.root, expected, 'should build the correct tree')
Пример #6
0
def test_insert_one_word():
    root_node = Trie()
    root_node.insert("Dimitar")

    expected = ['Dimitar']
    output = root_node.get_words(root_node)
    assert output == expected
Пример #7
0
    def test_insert_with_two_different_words_with_same_prefix(self):
        t = Trie()
        t.insert('alexandru')
        t.insert('alexandra')
        t.insert('alexandrul')

        expected = {'a': {'l': {'e': {'x': {'a': {'n': {'d': {'r': {'a': {END: None}, 'u': {END: None, 'l': {END: None}}}}}}}}}}}
        self.assertEqual(t.root, expected, 'should build the correct tree')
Пример #8
0
def test_insert_same_word_different_case():
    root_node = Trie()
    root_node.insert("dimitar")
    root_node.insert("DIMITAR")

    expected = ['dimitar', 'DIMITAR']
    output = root_node.get_words(root_node)
    assert output == expected
Пример #9
0
    def test_traverse(self):
        keys = ['foo', 'bar', 'baz', 'barz']
        t = Trie()
        map(lambda k: t.insert(k), keys)

        actual = t.traverse()
        expected = [('barz', None), ('bar', None), ('baz', None), ('foo', None)]
        self.assertEqual(expected, actual,
            'should return the keys in a sorted lexicographical order')
Пример #10
0
    def test_with_prefix(self):
        t = Trie()
        for (k, v) in [('foo', 1), ('bar', 2), ('baz', 3), ('bat', 4)]:
            t.insert(k, v)

        actual = t.with_prefix('ba')
        expected = [('bar', 2), ('baz', 3), ('bat', 4)]
        self.assertItemsEqual(actual, expected,
            'should export the correct values')
Пример #11
0
class ReverseDNS(object):
    def __init__(self):
        self.storage = Trie()

    def insert(self, ip, url):
        self.storage.insert(ip, url)

    def lookup(self, ip):
        return self.storage.lookup(ip)
Пример #12
0
class ReverseDNS(object):

    def __init__(self):
        self.storage = Trie()

    def insert(self, ip, url):
        self.storage.insert(ip, url)

    def lookup(self, ip):
        return self.storage.lookup(ip)
	def test__trie_auto_complete_query(self):
		my_trie = Trie()
		my_trie.insert('bark')
		my_trie.insert('bar')
		my_trie.insert('bark')
		results  = my_trie.auto_complete_query('ba', 2)
		self.assertEqual(results, [(1,'bar'), (2, 'bark')])
Пример #14
0
    def test_contains(self):
        t = Trie()
        t.insert('home')
        t.insert('homework')

        self.assertFalse(t.contains('ho'), 'prefix does not count as a key')
        self.assertTrue(t.contains('home'), 'should have found the key')
        self.assertTrue(t.contains('homework'), 'should have found the key')
        self.assertFalse(t.contains('homeworker'), 'should have found the key')
Пример #15
0
    def test_get_words_constrained(self):
        trieRoot = Trie.words()

        board = Board()
        testCoord = Coord(4, 8)
        startWord = "cabriole"
        startCoord = Coord(3, 7)
        board.place(("c", "a", "b", "r", "i", "o", "l", "e"), startCoord, True)

        tiles = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

        start = StartSequence(
            4, 6, [None, "a", None, None, None, None, None, None, None], False)
        plays = trieRoot.get_words_constrained(start, tiles, board)
        plays = [tuple(play) for play in plays]

        self.assertEqual(
            set(plays), {('b', None), ('b', None, 'd'), ('b', None, 'd', 'e'),
                         ('b', None, 'd', 'g', 'e'), ('b', None, 'a'),
                         ('b', None, 'a', 'e', 'd'), ('b', None, 'g'),
                         ('f', None), ('f', None, 'd'), ('f', None, 'd', 'e'),
                         ('f', None, 'd', 'g', 'e'), ('f', None, 'c', 'e'),
                         ('f', None, 'c', 'e', 'd'),
                         ('f', None, 'c', 'a', 'd', 'e'), ('f', None, 'g'),
                         ('d', None), ('d', None, 'b'), ('d', None, 'c', 'e'),
                         ('d', None, 'g'), ('a', None), ('c', None, 'b'),
                         ('c', None, 'f', 'e'), ('c', None, 'd'),
                         ('c', None, 'd', 'e'), ('c', None, 'd', 'g', 'e'),
                         ('c', None, 'g', 'e'), ('c', None, 'g', 'e', 'd'),
                         ('g', None, 'b'), ('g', None, 'e'),
                         ('g', None, 'e', 'd'), ('g', None, 'd')})

        board.place(plays[10], Coord(start.x, start.y), start.ish)
Пример #16
0
 def test_contains(self):
     # insert a word into trie
     t = Trie()
     t.insert("abba")
     self.assertTrue(t.contains("abba"))
     self.assertFalse(t.contains("hen"))
     self.assertFalse(t.contains("ab"))
Пример #17
0
    def test_get_char(self):
        trieRoot = Trie.words()

        template = ["c", "a", "b", None, "i", "o", "l", "e"]
        self.assertEqual(trieRoot.get_chars(template), ["r"])
        template = ["c", "a", None]

        invalid_template = ["s", None, None, "e"]
        self.assertRaises(RuntimeError,
                          lambda: trieRoot.get_chars(invalid_template))
Пример #18
0
    def test_score_words(self):
        trieRoot = Trie.words()
        b5 = Board(15)
        play = StartSequence(6, 7, ["b", "u", "g"], True)
        score = trieRoot.score_play(play, b5)
        self.assertEqual(score, 12)

        b5.place(["p", "a", "r", "k"], Coord(7, 5), False)
        play = StartSequence(1, 4, ["z", "e", "a", "l", "o", "t", "s"], True)
        score = trieRoot.score_play(play, b5)
        self.assertEqual(score, 42)
Пример #19
0
    def test_remove_tiles(self):
        b = Board(3)
        b.place(("b", "u", "g"), Coord(1, 0), False)

        tiles = ["a", "e", "i", "o", "u", "y"]
        ai = Ai("", tiles)

        trie = Trie.words()

        successful_play = ai.make_play(trie, b)
        self.assertNotEqual(len(ai.tiles), 7)
Пример #20
0
    def test_make_play(self):
        b = Board(3)
        b.place(("b", "u", "g"), Coord(1, 0), False)

        tiles = ["a", "e", "i", "o", "u", "y"]
        ai = Ai("", tiles)

        trie = Trie.words()

        successful_play = ai.make_play(trie, b)
        self.assertTrue(successful_play)
Пример #21
0
    def test_lookup(self):
        t = Trie()
        for (k, v) in [('bar', 1), ('baz', 2), ('buf', 3), ('buz', 4)]:
            t.insert(k, v)

        self.assertEqual(t.lookup('bar'), 1, 'should find the correct key')
        self.assertIsNone(t.lookup('bus'), 'detect when a key is not present')
        self.assertIsNone(t.lookup('foo'), 'detect when a key is not present')
        self.assertIsNone(t.lookup('bazar'), 'key prefix is present but not key')
        self.assertIsNone(t.lookup('ba'), 'prefix of existing key does not have a value')
Пример #22
0
    def __init__(self):
        self.bag = Bag()
        self.board = Board()
        self.trie = Trie.words()

        tiles1, tiles2 = [], []
        for _ in range(7):
            tiles1.append(self.bag.draw_tile())
            tiles2.append(self.bag.draw_tile())
        self.player1 = Ai("Player 1", tiles1)
        self.player2 = Ai("Player 2", tiles2)
        self.cur_player = self.player1
        self.skipped_turns = 0
Пример #23
0
    def __init__(self, size = 15, trie = None):
        if size < 1 or size % 2 == 0:
            raise RuntimeError(f"Invalid board dimension {size}")
        mid = size // 2
        self.size = size

        self.trie = trie if trie else Trie.words()
        self.tiles = [[None] * size for _ in range(size)]
        self.crosschecks = [[CrosscheckSquare() for _ in range(size)] for _ in range(size)]

        self.neighbors = [[False] * size for _ in range(size)]
        self.neighbors[mid][mid] = True
        self.neighbors_set = {Coord(mid, mid)}
	def test_traverse_prefix(self):
		my_trie = Trie()
		my_trie.insert('bark')
		my_trie.insert('bar')
		trie_node = my_trie.traverse_prefix('bar')
		self.assertEqual(trie_node.char, 'r')
		self.assertEqual(trie_node.val, 1)
		arr = [None] * 27
		arr[10] = Node(10)
		self.assertEqual(trie_node.children[10].char, arr[10].char)
		self.assertEqual(trie_node.children[10].val, 1)
Пример #25
0
    def test_make_play_fail(self):
        b = Board(3)
        b.place(["b", "u", "g"], Coord(0, 0), True)
        b.place(["a", "g", "o"], Coord(0, 1), True)
        # b.place(["a", "g"], Coord(0, 2), True)
        b.place(["x", "x"], Coord(0, 2), True)

        tiles = ["e", "i", "u", "y"]
        ai = Ai("", tiles)
        trie = Trie.words()

        successful_play = ai.make_play(trie, b)
        self.assertFalse(successful_play)
Пример #26
0
def test_get_words_one_word():
    root_node = Trie()
    trie_1 = Trie('C')
    trie_2 = Trie('A')
    trie_3 = Trie('R')
    root_node.children[trie_1.value] = trie_1
    trie_1.children[trie_2.value] = trie_2
    trie_2.children[trie_3.value] = trie_3

    expected = ['CAR']
    output = root_node.get_words(root_node)
    assert output == expected
Пример #27
0
    def test_get_words_constrained_full(self):
        trieRoot = Trie.words()
        b4 = Board(3)
        b4.place(("b", "u", "g"), Coord(1, 0), False)

        starts = b4.get_starts(6)
        words = []
        tiles = ["a", "e", "i", "o", "u", "y"]

        for start in starts:
            words.extend(trieRoot.get_words_constrained(start, tiles, b4))
        words = [tuple(word) for word in words]

        self.assertEqual(
            set(words), {('a', None, 'o'), ('a', None, 'y'), ('o', None, 'e'),
                         ('o', None, 'i'), (None, 'e'), (None, 'a'),
                         (None, 'i'), (None, 'o'), (None, 'y'), (None, 'o'),
                         ('e', None, 'o'), ('a', None), ('a', None, 'e'),
                         ('a', None, 'o')})
Пример #28
0
    def test_update_neighbors(self):

        trieRoot = Trie.words()

        board = Board()
        testCoord = Coord(4, 8)
        startWord = "cabriole"
        startCoord = Coord(3, 7)
        board.place(["c", "a", "b", "r", "i", "o", "l", "e"], startCoord, True)
        # not a neighbor
        self.assertEqual(board.neighbors[9][4], False)
        # occupied
        self.assertEqual(board.neighbors[7][6], False)
        # should be neighbors
        self.assertEqual(board.neighbors[7][2], True)
        self.assertEqual(board.neighbors[6][9], True)
        self.assertEqual(board.neighbors[8][9], True)
        self.assertEqual(board.neighbors[7][11], True)

        starts = board.get_starts(5)
Пример #29
0
    def test_crosscheck(self):
        trieRoot = Trie.words()

        board = Board()
        testCoord = Coord(4, 8)
        # should be empty set
        expected = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z'}
        self.assertEqual(board.get_v_check(testCoord), expected)

        startWord = "cabriole"
        startCoord = Coord(3, 7)
        board.place_word(startWord, startCoord, True)
        board.update_state(startCoord, len(startWord), True)
        # after placing "cabriole" at (7,3), v crosscheck for (8, 4) should be:
        expected = {'i', 's', 'e', 'w', 'g', 'm', 'n', 'l', 'd', 'a', 'y', 'x',
                    't', 'h', 'r'}
        self.assertEqual(board.get_v_check(testCoord), expected)

        board = Board()
        board.place_word(startWord, Coord(7, 3), False)
        board.update_state(Coord(7, 3), len(startWord), False)
        self.assertEqual(board.get_h_check(Coord(8, 4)), expected)
Пример #30
0
class BaseSegment:
    def __init__(self):
        self.trie = Trie()

    def cut(self, sentence: str):
        pass

    def load_dict(self, file: str):
        if not os.path.exists(file):
            print('%s 不存在!' % file)
            return

        with open(file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                line = line.split()
                if len(line) == 3:
                    self.trie.insert(line[0], int(line[1]), line[2])
                elif len(line) == 2:
                    self.trie.insert(line[0], int(line[1]))
                else:
                    self.trie.insert(line[0])
        f.close()
        print('词典加载完成!')
Пример #31
0
def test_insert_multiple_words():
    root_node = Trie()
    root_node.insert('BEAR')
    root_node.insert('BELL')
    root_node.insert('BID')
    root_node.insert('BULL')
    root_node.insert('BUY')
    root_node.insert('SELL')
    root_node.insert('STOCK')
    root_node.insert('STOP')

    expected = ['BEAR', 'BELL', 'BID', 'BULL', 'BUY', 'SELL', 'STOCK', 'STOP']
    output = root_node.get_words(root_node)
    assert output == expected
Пример #32
0
def test_get_words_multiple_words():
    root_node = Trie()
    trie_L1_1 = Trie('A')
    trie_L1_2 = Trie('B')
    trie_L1_3 = Trie('C')

    trie_L2_1 = Trie('T')
    trie_L2_2 = Trie('R')    
    trie_L2_3 = Trie('A')
    trie_L2_4 = Trie('N')
    trie_L2_5 = Trie('E')

    root_node.children[trie_L1_1.value] = trie_L1_1
    root_node.children[trie_L1_2.value] = trie_L1_2
    root_node.children[trie_L1_3.value] = trie_L1_3
    trie_L1_1.children[trie_L2_1.value] = trie_L2_1
    trie_L1_1.children[trie_L2_2.value] = trie_L2_2
    trie_L1_2.children[trie_L2_3.value] = trie_L2_3
    trie_L1_3.children[trie_L2_4.value] = trie_L2_4
    trie_L1_3.children[trie_L2_5.value] = trie_L2_5

    expected = ['AT', 'AR', 'BA', 'CN', 'CE']
    output = root_node.get_words(root_node)
    assert output == expected
Пример #33
0
def test_search_basic_with_multiple_words():
    root_node = Trie()
    root_node.insert('BEAR')
    root_node.insert('BELL')
    root_node.insert('BID')
    root_node.insert('BULL')
    root_node.insert('BUY')
    root_node.insert('SELL')
    root_node.insert('STOCK')
    root_node.insert('STOP')

    expected = True
    output = root_node.search('BULL')
    assert output == expected
Пример #34
0
def test_search_blank_empty_trie():
    root_node = Trie()

    expected = False
    output = root_node.search('')
    assert output == expected
Пример #35
0
def test_get_words_multiple_words_complex():
    root_node = Trie()
    trie_L1_1 = Trie('B')
    trie_L1_2 = Trie('S')
    trie_L2_1 = Trie('E')
    trie_L2_2 = Trie('I')    
    trie_L2_3 = Trie('U')
    trie_L2_4 = Trie('E')
    trie_L2_5 = Trie('T')
    trie_L3_1 = Trie('A')
    trie_L3_2 = Trie('L')    
    trie_L3_3 = Trie('D')
    trie_L3_4 = Trie('L')
    trie_L3_5 = Trie('Y')
    trie_L3_6 = Trie('L')
    trie_L3_7 = Trie('O')
    trie_L4_1 = Trie('R')
    trie_L4_2 = Trie('L')    
    trie_L4_3 = Trie('L')
    trie_L4_4 = Trie('L')
    trie_L4_5 = Trie('C')
    trie_L4_6 = Trie('P')
    trie_L5_1 = Trie('K')

    root_node.children[trie_L1_1.value] = trie_L1_1
    root_node.children[trie_L1_2.value] = trie_L1_2
    trie_L1_1.children[trie_L2_1.value] = trie_L2_1
    trie_L1_1.children[trie_L2_2.value] = trie_L2_2
    trie_L1_1.children[trie_L2_3.value] = trie_L2_3
    trie_L1_2.children[trie_L2_4.value] = trie_L2_4
    trie_L1_2.children[trie_L2_5.value] = trie_L2_5
    trie_L2_1.children[trie_L3_1.value] = trie_L3_1
    trie_L2_1.children[trie_L3_2.value] = trie_L3_2
    trie_L2_2.children[trie_L3_3.value] = trie_L3_3
    trie_L2_3.children[trie_L3_4.value] = trie_L3_4
    trie_L2_3.children[trie_L3_5.value] = trie_L3_5
    trie_L2_4.children[trie_L3_6.value] = trie_L3_6
    trie_L2_5.children[trie_L3_7.value] = trie_L3_7
    trie_L3_1.children[trie_L4_1.value] = trie_L4_1
    trie_L3_2.children[trie_L4_2.value] = trie_L4_2
    trie_L3_4.children[trie_L4_3.value] = trie_L4_3
    trie_L3_6.children[trie_L4_4.value] = trie_L4_4
    trie_L3_7.children[trie_L4_5.value] = trie_L4_5
    trie_L3_7.children[trie_L4_6.value] = trie_L4_6
    trie_L4_5.children[trie_L5_1.value] = trie_L5_1

    expected = ['BEAR', 'BELL', 'BID', 'BULL', 'BUY', 'SELL', 'STOCK', 'STOP']
    output = root_node.get_words(root_node)
    assert output == expected
Пример #36
0
def simple_trie(scope="function"):
    x = Trie()
    x.insert("Norton")
    x.insert("North")
    x.insert("Nortron")
    x.insert("Nord")
    x.insert("No")
    return x
Пример #37
0
 def __init__(self):
     self.storage = Trie()
Пример #38
0
def testTrie():
    '''
    Here we test algorithms for a trie tree
    We test insert, search, and start-with functions
    Each node of the trie tree is an object of
    the TrieNode class, which has
    a. children hash that stores characters as hash keys
    b. endOfWord boolean indicator
    '''

    print('Create an empty trie')
    t = Trie()
    print('apple exists? ' + str(t.search('apple')))
    print('\"\" exists? ' + str(t.search('')))
    print('\"\" prefix exists? ' + str(t.startsWith('')))
    print('Insert apple')
    t.insert('apple')
    print('apple exists? ' + str(t.search('apple')))
    print('app exists? ' + str(t.search('app')))
    print('app prefix exists? ' + str(t.startsWith('app')))
    print('appe prefix exists? ' + str(t.startsWith('appe')))
    print('Insert app')
    t.insert('app')
    print('app exists? ' + str(t.search('app')))
    print('Insert @pple')
    t.insert('@pple')
    print('@pple exists? ' + str(t.search('@pple')))
Пример #39
0
def test_search_empty_trie():
    root_node = Trie()

    expected = False
    output = root_node.search("Dog")
    assert output == expected
Пример #40
0
 def __init__(self):
     self.storage = Trie()