예제 #1
0
 def test_addingChildren(self):
     c = Node("c", False)
     a = Node("a", False)
     t = Node("t", True, "cat")
     c.addChild(a)
     a.addChild(t)
     self.assertEqual(c.children, {"a": a})
     self.assertEqual(a.children, {"t": t})
예제 #2
0
    def __init__(self, vocabulary, max_completions=5):
        self.max_completions = max_completions
        self.length = 0
        self.root = Node('.', 0, None)
        if isinstance(vocabulary, list):
            for i in range(len(vocabulary)):
                self.insert(vocabulary[i])
        elif isinstance(vocabulary, str):
            try:
                with open(vocabulary) as dictionary:
                    data = dictionary.read()
                    data = data.split('\n')
                for i in range(len(data)):
                    x = i / len(data) * 100
                    sys.stdout.write("\r%d%%" % x)
                    sys.stdout.flush()
                    self.insert(data[i])
            except FileNotFoundError:

                raise FileNotFoundError('Please enter valid list or file path.')
예제 #3
0
	for neighbor in node.getNeighbors():
		if neighbor not in visited:
			results = algorithm(head[neighbor.getValue()], neighbor, visited)
			found.extend([head.getLetter() + ending for ending in results])

	visited.remove(node)
	return found

# Main code execution, needs to be wrapped up.
# Passes in a board string, creates the board in
# an array, setups the connections, creates a trie
# from the dictionary and then iterates over each
# starting point on the board as the head node and
# returns found words.
RUZZLE_PUZZLE = "TIMILNEDEAOMTCAR".lower()
board = [Node(letter) for letter in RUZZLE_PUZZLE]
createConnections(board, RUZZLE_PUZZLE)
trie = createTrie('ruzzle_dictionary.txt')

results = []
for node in board:
	head = trie
	if head[node.getValue()]:
		found_words = algorithm(head[node.getValue()], node)

		if len(found_words) > 0:
			results.extend(found_words)

results = list(set(results))
output = sorted(results, key=lambda word: [len(word)], reverse=True)
예제 #4
0
from flask import Flask, request, jsonify
from trie import Node
from tqdm import tqdm

app = Flask(__name__, static_url_path='')
root = Node()


@app.route("/search", methods=["GET"])
def search():
    prefix = request.args.get("q", "")
    return jsonify({"results": root.search(prefix)})


@app.route('/')
def default():
    return app.send_static_file("index.html")


@app.route('/<path:path>')
def send_static(path):
    return app.send_static_file(path)


def initialize_trie():
    with open("domains.csv", "r") as f:
        for line in tqdm(f.readlines()):
            parts = line.split(",")
            domain = parts[1].strip()
            root.insert(domain)
예제 #5
0
# Custom objects know their class.
# Function objects seem to know way too much, including modules.
# Exclude modules as well.
BLACKLIST = type, ModuleType, FunctionType


def getsize(obj):
    """sum size of object & members."""
    if isinstance(obj, BLACKLIST):
        raise TypeError('getsize() does not take argument of type: '+ str(type(obj)))
    seen_ids = set()
    size = 0
    objects = [obj]
    while objects:
        need_referents = []
        for obj in objects:
            if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids:
                seen_ids.add(id(obj))
                size += sys.getsizeof(obj)
                need_referents.append(obj)
        objects = get_referents(*need_referents)
    return size

from trie import Node
from collections import defaultdict

print(getsize(Node('a')))

print(getsize({}))
print(getsize(defaultdict(list)))
예제 #6
0
def test_trie_node_init_no_values_two():
    """Test the trie node init method, end value with no input values."""
    from trie import Node
    test_case = Node()
    assert test_case.end is False
예제 #7
0
def test_created_node_has_attributes():
    """Test attributes of Node."""
    n = Node()
    assert n.letter is None
    assert n.children == {}
    assert n.end is False
예제 #8
0
 def test_has_data(self):
     node = Node()
     self.assertFalse(node.has_data())
     node.data = 1
     self.assertTrue(node.has_data())
예제 #9
0
def test_node_init_object():
    """Test initialization node object."""
    n = Node()
    assert isinstance(n, Node)
예제 #10
0
 def test_creation(self):
     node = Node("b", False)
     self.assertEqual(node.letter, "b")
     self.assertFalse(node.endOfWord)
     self.assertEqual(node.children, {})
     self.assertEqual(node.fullWord, "")
예제 #11
0
 def test_init_node(self):
     node = Node()
     self.assertIsNone(node.data)
     self.assertEqual(len(node.children), 0)
예제 #12
0
 def test_has_data(self):
     node = Node()
     self.assertFalse(node.has_data())
     node.data = 1
     self.assertTrue(node.has_data())
예제 #13
0
def test_trie_node_init_no_values_one():
    """Test the trie node init method, lookup value with no input values."""
    from trie import Node
    test_case = Node()
    assert test_case.lookup == {}
예제 #14
0
def test_trie_node_init_inputs_two():
    """Test the trie node init method, end value with appropriate input."""
    from trie import Node
    test_case = Node("a", True)
    assert test_case.end is True
예제 #15
0
def test_trie_node_init_inputs_one():
    """Test the trie node init method, lookup value with appropriate input."""
    from trie import Node
    test_case = Node("a", True)
    assert test_case.lookup["a"] == []
예제 #16
0
def test_node_init_children():
    """Test initialization object, children."""
    n = Node()
    assert n.children == {}
예제 #17
0
def test_node_init_terminus():
    """Test initialization node, terminus."""
    n = Node()
    assert n.terminus is False
예제 #18
0
 def test_getting_children(self):
     c = Node("c", False)
     a = Node("a", False)
     t = Node("t", True, "cat")
     c.addChild(a)
     a.addChild(t)
     self.assertEqual(c.getChild("a"), a)
     self.assertEqual(a.getChild("t"), t)
     self.assertEqual(c.getChild("b"), Node("", False))
예제 #19
0
def test_node_initialized_with_attrs():
    """Test if node is initialized with attributes."""
    from trie import Node
    new_node = Node('k')
    assert new_node.val == 'k'
예제 #20
0
from trie import Trie, Node
import sys
from utils import alphabet, get_words_only, get_words_from_file
from messages import Messages

# TODO: use parseargs within parseargs for this?

if __name__ == '__main__':

    msgs = Messages()
    msgs['welcome']()

    t = Trie(Node(None))
    candidate = ''
    while True:
        cmd = str(input('>>> ').strip())

        if cmd.startswith(':'):
            cmd = cmd[1:]

            if cmd == 'q':
                msgs['close']()
                sys.exit(0)
            elif cmd == 'f':
                filename = str(
                    input('Enter a qualified filepath:\n>>> ').strip())
                words = get_words_from_file(filename)
                for word in words:
                    msgs['adding_to_trie'](word)
                    t.insert(word)
            elif cmd == 'a':
예제 #21
0
import fileinput
from trie import Node

punctuation = ['.', '?', '!', ';', ',']
dict = Node('root')
searched = {}


# iterates through dictionary file and adds
# all words to a trie for fast searching
def loadDict():
    file = fileinput.input(files=('dictionary.txt'))
    lineNo = 1
    wordsToSkip = [
        'ing', 'en', 'aut', 'de', 'ful', 'uti', 'n\'t', 'goe', 'dra', 'andra',
        '\'t', 'ble', 'eth', 'et'
    ]
    for l in file:
        line = l.strip()
        if "#!comment" not in line and line not in wordsToSkip and (
                len(line) > 2 or line == "a" or line == "A" or line == "I"
                or lineNo <= 200):
            lineNo += 1
            dict.add(line)
    file.close()


# goes through and adds spaces around punctuation
# to increase accuracy of the program's output
def preProcess(str):
    res = []
예제 #22
0
 def setUp(self):
     self.node = Node(1)
예제 #23
0
 def test_pre_order_two(self):
     root = Node()
     for l in 'ABCDE':
         root.add_or_fetch_child(l)
     po = [n._element for n in root.pre_order() if n._element != None]
     map(self.assertEqual, po, 'ABCDE')
예제 #24
0
def main():
    root = Node('root')
    Node.add(root, "bear")
    Node.add(root, "bell")
    Node.add(root, "bid")
    Node.add(root, "bull")
    Node.add(root, "buy")
    Node.add(root, "sell")
    Node.add(root, "stock")
    Node.add(root, "stop")

    print(root.search("sto", True))
    print(root.search("sto", False))
    print(root.search("stop", True))

    root.pprint()