Example #1
0
def test_LinkedListQueue():
    q1 = Queue(implementation='linked_list')
    q1.append(1)
    assert raises(TypeError, lambda: Queue(implementation='linked_list', items={0, 1}))
    q1 = Queue(implementation='linked_list', items = [0, 1])
    q1.append(2)
    q1.append(3)
    assert str(q1) == '[0, 1, 2, 3]'
    assert len(q1) == 4
    assert q1.popleft().data == 0
    assert q1.popleft().data == 1
    assert len(q1) == 2
    assert q1.popleft().data == 2
    assert q1.popleft().data == 3
    assert len(q1) == 0
    raises(IndexError, lambda: q1.popleft())

    q1 = Queue(implementation='linked_list',items=['a',None,type,{}])
    assert len(q1) == 4
    assert q1.size == 4

    front = q1.front
    assert front.data == q1.popleft().data

    rear = q1.rear
    for _ in range(len(q1)-1):
        q1.popleft()

    assert rear.data == q1.popleft().data
def test_SinglyCircularLinkedList():
    random.seed(1000)
    scll = SinglyCircularLinkedList()
    assert raises(IndexError, lambda: scll[2])
    scll.appendleft(5)
    scll.append(1)
    scll.appendleft(2)
    scll.append(3)
    scll.insert_after(scll[1], 4)
    scll.insert_after(scll[-1], 6)
    scll.insert_at(0, 2)
    scll.insert_at(-1, 9)
    scll.extract(2)
    assert scll.popleft().key == 2
    assert scll.popright().key == 6
    assert scll.search(-1) is None
    scll[-2].key = 0
    assert str(scll) == "['2', '4', '1', '0', '9']"
    assert len(scll) == 5
    assert raises(IndexError, lambda: scll.insert_at(6, None))
    assert raises(IndexError, lambda: scll.extract(20))
    scll_copy = DoublyCircularLinkedList()
    for i in range(scll.size):
        scll_copy.append(scll[i])
    for i in range(len(scll)):
        if i % 2 == 0:
            scll.popleft()
        else:
            scll.popright()
    assert str(scll) == "[]"
    for _ in range(len(scll_copy)):
        index = random.randint(0, len(scll_copy) - 1)
        scll_copy.extract(index)
    assert str(scll_copy) == "[]"
    assert raises(ValueError, lambda: scll_copy.extract(1))
Example #3
0
def test_LinkedListStack():
    s = Stack(implementation='linked_list')
    s.push(1)
    s.push(2)
    s.push(3)
    assert s.peek.key == 3
    assert str(s) == ("['(1, None)', '(2, None)', '(3, None)']")
    assert s.pop().key == 3
    assert s.pop().key == 2
    assert s.pop().key == 1
    assert s.is_empty is True
    assert raises(IndexError, lambda: s.pop())
    assert str(s) == '[]'
    _s = Stack(implementation='linked_list', items=[1, 2, 3])
    assert str(_s) == "['(1, None)', '(2, None)', '(3, None)']"
    assert len(_s) == 3

    s = Stack(implementation='linked_list', items=['a', None, type, {}])
    assert len(s) == 4
    assert s.size == 4

    peek = s.peek
    assert peek.key == s.pop().key
    assert raises(TypeError,
                  lambda: Stack(implementation='linked_list', items={0, 1}))
def test_DoublyLinkedList():
    random.seed(1000)
    dll = DoublyLinkedList()
    assert raises(IndexError, lambda: dll[2])
    dll.append_left(5)
    dll.append(1)
    dll.append_left(2)
    dll.append(3)
    dll.insert_after(dll[-1], 4)
    dll.insert_after(dll[2], 6)
    dll.insert_before(dll[4], 1)
    dll.insert_before(dll[0], 7)
    dll.insert_at(0, 2)
    dll.insert_at(-1, 9)
    dll.extract(2)
    dll.extract(0)
    dll.extract(-1)
    dll[-2].data = 0
    assert str(dll) == "[7, 5, 1, 6, 1, 0, 9]"
    assert len(dll) == 7
    assert raises(IndexError, lambda: dll.insert_at(8, None))
    assert raises(IndexError, lambda: dll.extract(20))
    dll_copy = copy.deepcopy(dll)
    for i in range(len(dll)):
        if i % 2 == 0:
            dll.pop_left()
        else:
            dll.pop_right()
    assert str(dll) == "[]"
    for _ in range(len(dll_copy)):
        index = random.randint(0, len(dll_copy) - 1)
        dll_copy.extract(index)
    assert str(dll_copy) == "[]"
    assert raises(ValueError, lambda: dll_copy.extract(1))
def test_SinglyLinkedList():
    random.seed(1000)
    sll = SinglyLinkedList()
    assert raises(IndexError, lambda: sll[2])
    sll.append_left(5)
    sll.append(1)
    sll.append_left(2)
    sll.append(3)
    sll.insert_after(sll[1], 4)
    sll.insert_after(sll[-1], 6)
    sll.insert_at(0, 2)
    sll.insert_at(-1, 9)
    sll.extract(2)
    sll.extract(0)
    sll.extract(-1)
    sll[-2].data = 0
    assert str(sll) == "[2, 4, 1, 0, 9]"
    assert len(sll) == 5
    assert raises(IndexError, lambda: sll.insert_at(6, None))
    assert raises(IndexError, lambda: sll.extract(20))
    sll_copy = copy.deepcopy(sll)
    for i in range(len(sll)):
        if i % 2 == 0:
            sll.pop_left()
        else:
            sll.pop_right()
    assert str(sll) == "[]"
    for _ in range(len(sll_copy)):
        index = random.randint(0, len(sll_copy) - 1)
        sll_copy.extract(index)
    assert str(sll_copy) == "[]"
    assert raises(ValueError, lambda: sll_copy.extract(1))
def test_AdjacencyMatrix():
    v_0 = AdjacencyMatrixGraphNode(0, 0)
    v_1 = AdjacencyMatrixGraphNode(1, 1)
    v_2 = AdjacencyMatrixGraphNode(2, 2)
    g = Graph(v_0, v_1, v_2)
    g.add_edge(0, 1, 0)
    g.add_edge(1, 2, 0)
    g.add_edge(2, 0, 0)
    e1 = g.get_edge(0, 1)
    e2 = g.get_edge(1, 2)
    e3 = g.get_edge(2, 0)
    assert (e1.source.name, e1.target.name) == ('0', '1')
    assert (e2.source.name, e2.target.name) == ('1', '2')
    assert (e3.source.name, e3.target.name) == ('2', '0')
    assert g.is_adjacent(0, 1) is True
    assert g.is_adjacent(1, 2) is True
    assert g.is_adjacent(2, 0) is True
    assert g.is_adjacent(1, 0) is False
    assert g.is_adjacent(2, 1) is False
    assert g.is_adjacent(0, 2) is False
    neighbors = g.neighbors(0)
    assert neighbors == [v_1]
    g.remove_edge(0, 1)
    assert g.is_adjacent(0, 1) is False
    assert raises(ValueError, lambda: g.add_edge('u', 'v'))
    assert raises(ValueError, lambda: g.add_edge('v', 'x'))
    assert raises(ValueError, lambda: g.add_edge(2, 3))
    assert raises(ValueError, lambda: g.add_edge(3, 2))
Example #7
0
def test_BinarySearchTree():
    BST = BinarySearchTree
    b = BST(8, 8)
    b.insert(3, 3)
    b.insert(10, 10)
    b.insert(1, 1)
    b.insert(6, 6)
    b.insert(4, 4)
    b.insert(7, 7)
    b.insert(14, 14)
    b.insert(13, 13)
    assert str(b) == \
    ("[(1, 8, 8, 2), (3, 3, 3, 4), (None, 10, 10, 7), (None, 1, 1, None), "
    "(5, 6, 6, 6), (None, 4, 4, None), (None, 7, 7, None), (8, 14, 14, None), "
    "(None, 13, 13, None)]")
    assert b.search(10) == 2
    assert b.search(-1) == None
    assert b.delete(13) == True
    assert b.search(13) == None
    assert b.delete(10) == True
    assert b.search(10) == None
    assert b.delete(3) == True
    assert b.search(3) == None
    assert b.delete(13) == None
    assert str(b) == \
    ("[(1, 8, 8, 7), (3, 4, 4, 4), (None, 10, 10, 7), (None, 1, 1, None), "
    "(None, 6, 6, 6), (None, 4, 4, None), (None, 7, 7, None), (None, 14, 14, None), "
    "(None, 13, 13, None)]")
    bc = BST(1, 1)
    assert bc.insert(1, 2) == None
    raises(ValueError, lambda: BST(root_data=6))
Example #8
0
def test_ArrayQueue():
    q1 = Queue()
    raises(IndexError, lambda: q1.popleft())
    q1 = Queue(implementation='array', items=[0])
    q1.append(1)
    q1.append(2)
    q1.append(3)
    assert str(q1) == '[0, 1, 2, 3]'
    assert len(q1) == 4
    assert q1.popleft() == 0
    assert q1.popleft() == 1
    assert len(q1) == 2
    assert q1.popleft() == 2
    assert q1.popleft() == 3
    assert len(q1) == 0

    q2 = Queue(implementation='array', items=[0], double_ended=True)
    q2.append(1)
    q2.append(2)
    q2.appendleft(3)
    assert str(q2) == '[3, 0, 1, 2]'
    assert len(q2) == 4
    assert q2.popleft() == 3
    assert q2.pop() == 2
    assert len(q2) == 2
    assert q2.popleft() == 0
    assert q2.pop() == 1
    assert len(q2) == 0

    q1 = Queue(implementation='array', items=[0])
    assert raises(NotImplementedError, lambda: q1.appendleft(2))
Example #9
0
def test_BinomialTree():
    assert raises(TypeError, lambda: BinomialTree(1, 1))
    assert raises(TypeError, lambda: BinomialTree(None, 1.5))

    bt = BinomialTree()
    assert raises(TypeError, lambda: bt.add_sub_tree(None))
    bt1 = BinomialTree(BinomialTreeNode(1, 1), 0)
    node = BinomialTreeNode(2, 2)
    node.add_children(BinomialTreeNode(3, 3))
    bt2 = BinomialTree(node, 1)
    assert raises(ValueError, lambda: bt1.add_sub_tree(bt2))
    assert bt1.is_empty is False
Example #10
0
def test_MultiDimensionalArray():
    assert raises(ValueError, lambda: MultiDimensionalArray(int, 2, -1, 3))
    assert MultiDimensionalArray(int, 10).shape == (10, )
    array = MultiDimensionalArray(int, 5, 9, 3, 8)
    assert array.shape == (5, 9, 3, 8)
    array.fill(5)
    array[1, 3, 2, 5] = 2.0
    assert array
    assert array[1, 3, 2, 5] == 2.0
    assert array[1, 3, 0, 5] == 5
    assert array[1, 2, 2, 5] == 5
    assert array[2, 3, 2, 5] == 5
    assert raises(IndexError, lambda: array[5])
    assert raises(IndexError, lambda: array[4, 10])
    assert raises(IndexError, lambda: array[-1])
    assert raises(IndexError, lambda: array[2, 3, 2, 8])
    assert raises(ValueError, lambda: MultiDimensionalArray())
    assert raises(ValueError, lambda: MultiDimensionalArray(int))
    assert raises(TypeError, lambda: MultiDimensionalArray(int, 5, 6, ""))
    array = MultiDimensionalArray(int, 3, 2, 2)
    array.fill(1)
    array[0, 0, 0] = 0
    array[0, 0, 1] = 0
    array[1, 0, 0] = 0
    array[2, 1, 1] = 0
    assert str(array) == '[0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]'
    array = MultiDimensionalArray(int, 4)
    assert array.shape == (4, )
    array.fill(5)
    array[3] = 3
    assert array[3] == 3
Example #11
0
def test_ArrayQueue():
    q1 = Queue()
    raises(IndexError, lambda: q1.popleft())
    q1 = Queue(implementation='array', items=[0])
    q1.append(1)
    q1.append(2)
    q1.append(3)
    assert str(q1) == '[0, 1, 2, 3]'
    assert len(q1) == 4
    assert q1.popleft() == 0
    assert q1.popleft() == 1
    assert len(q1) == 2
    assert q1.popleft() == 2
    assert q1.popleft() == 3
    assert len(q1) == 0
Example #12
0
def test_Stack():

    s = Stack()
    s.push(1)
    s.push(2)
    s.push(3)
    assert s.peek == 3
    assert str(s) == '[1, 2, 3]'
    assert s.pop() == 3
    assert s.pop() == 2
    assert s.pop() == 1
    assert s.is_empty is True
    assert raises(ValueError, lambda : s.pop())
    _s = Stack(items=[1, 2, 3])
    assert str(_s) == '[1, 2, 3]'
    assert raises(NotImplementedError, lambda: Stack(implementation=''))
    def _test_shortest_paths(ds, algorithm):
        import pydatastructs.utils.misc_util as utils
        GraphNode = getattr(utils, "Adjacency" + ds + "GraphNode")
        vertices = [GraphNode('S'), GraphNode('C'),
                    GraphNode('SLC'), GraphNode('SF'),
                    GraphNode('D')]

        graph = Graph(*vertices)
        graph.add_edge('S', 'SLC', 2)
        graph.add_edge('C', 'S', 4)
        graph.add_edge('C', 'D', 2)
        graph.add_edge('SLC', 'C', 2)
        graph.add_edge('SLC', 'D', 3)
        graph.add_edge('SF', 'SLC', 2)
        graph.add_edge('SF', 'S', 2)
        graph.add_edge('D', 'SF', 3)
        dist, pred = shortest_paths(graph, algorithm, 'SLC')
        assert dist == {'S': 6, 'C': 2, 'SLC': 0, 'SF': 6, 'D': 3}
        assert pred == {'S': 'C', 'C': 'SLC', 'SLC': None, 'SF': 'D', 'D': 'SLC'}
        dist, pred = shortest_paths(graph, algorithm, 'SLC', 'SF')
        assert dist == 6
        assert pred == {'S': 'C', 'C': 'SLC', 'SLC': None, 'SF': 'D', 'D': 'SLC'}
        graph.remove_edge('SLC', 'D')
        graph.add_edge('D', 'SLC', -10)
        assert raises(ValueError, lambda: shortest_paths(graph, 'bellman_ford', 'SLC'))
Example #14
0
def test_matrix_multiply_parallel():
    ODA = OneDimensionalArray

    expected_result = [[3, 3, 3], [1, 2, 1], [2, 2, 2]]

    I = ODA(ODA,
            [ODA(int, [1, 1, 0]),
             ODA(int, [0, 1, 0]),
             ODA(int, [0, 0, 1])])
    J = ODA(ODA,
            [ODA(int, [2, 1, 2]),
             ODA(int, [1, 2, 1]),
             ODA(int, [2, 2, 2])])
    output = matrix_multiply_parallel(I, J, num_threads=5)
    assert expected_result == output

    I = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
    J = [[2, 1, 2], [1, 2, 1], [2, 2, 2]]
    output = matrix_multiply_parallel(I, J, num_threads=5)
    assert expected_result == output

    I = [[1, 1, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]
    J = [[2, 1, 2], [1, 2, 1], [2, 2, 2]]
    assert raises(ValueError,
                  lambda: matrix_multiply_parallel(I, J, num_threads=5))

    I = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
    J = [[2, 1, 2], [1, 2, 1], [2, 2, 2]]
    output = matrix_multiply_parallel(I, J, num_threads=1)
    assert expected_result == output
def test_LinkedListQueue():
    q1 = Queue(implementation='linked_list')
    q1.append(1)
    assert raises(TypeError,
                  lambda: Queue(implementation='linked_list', items={0, 1}))
    q1 = Queue(implementation='linked_list', items=[0, 1])
    q1.append(2)
    q1.append(3)
    assert str(q1) == ("['(0, None)', '(1, None)', "
                       "'(2, None)', '(3, None)']")
    assert len(q1) == 4
    assert q1.popleft().key == 0
    assert q1.popleft().key == 1
    assert len(q1) == 2
    assert q1.popleft().key == 2
    assert q1.popleft().key == 3
    assert len(q1) == 0
    raises(IndexError, lambda: q1.popleft())

    q1 = Queue(implementation='linked_list', items=['a', None, type, {}])
    assert len(q1) == 4

    front = q1.front
    assert front.key == q1.popleft().key

    rear = q1.rear
    for _ in range(len(q1) - 1):
        q1.popleft()

    assert rear.key == q1.popleft().key

    q1 = Queue(implementation='linked_list', double_ended=True)
    q1.appendleft(1)
    q2 = Queue(implementation='linked_list', items=[0, 1])
    assert raises(NotImplementedError, lambda: q2.appendleft(1))
    q1 = Queue(implementation='linked_list', items=[0, 1], double_ended=True)
    q1.appendleft(2)
    q1.append(3)
    assert str(q1) == "['(2, None)', '(0, None)', '(1, None)', '(3, None)']"
    assert len(q1) == 4
    assert q1.popleft().key == 2
    assert q1.pop().key == 3
    assert len(q1) == 2
    assert q1.pop().key == 1
    assert q1.popleft().key == 0
    assert len(q1) == 0
    assert raises(IndexError, lambda: q1.popleft())
Example #16
0
def test_Queue():
    q = Queue(implementation='array')
    q1 = Queue()
    assert _check_type(q, ArrayQueue) is True
    assert _check_type(q1, ArrayQueue) is True
    q2 = Queue(implementation='linked_list')
    assert _check_type(q2, LinkedListQueue) is True
    assert raises(NotImplementedError, lambda: Queue(implementation=''))
Example #17
0
def test_Stack():
    s = Stack(implementation='array')
    s1 = Stack()
    assert _check_type(s, ArrayStack) is True
    assert _check_type(s1, ArrayStack) is True
    s2 = Stack(implementation='linked_list')
    assert _check_type(s2, LinkedListStack) is True
    assert raises(NotImplementedError, lambda: Stack(implementation=''))
def test_DHeap():
    assert raises(ValueError, lambda: DHeap(heap_property="none", d=4))
    max_heap = DHeap(heap_property="max", d=5)
    assert raises(IndexError, lambda: max_heap.extract())
    max_heap.insert(100, 100)
    max_heap.insert(19, 19)
    max_heap.insert(36, 36)
    max_heap.insert(17, 17)
    max_heap.insert(3, 3)
    max_heap.insert(25, 25)
    max_heap.insert(1, 1)
    max_heap = DHeap(max_heap.heap, heap_property="max", d=4)
    max_heap.insert(2, 2)
    max_heap.insert(7, 7)
    assert str(max_heap) == \
           ('[(100, 100, [1, 2, 3, 4]), (25, 25, [5, 6, 7, 8]), '
           '(36, 36, []), (17, 17, []), (3, 3, []), (19, 19, []), '
           '(1, 1, []), (2, 2, []), (7, 7, [])]')

    assert max_heap.extract().key == 100

    expected_sorted_elements = [36, 25, 19, 17, 7, 3, 2, 1]
    sorted_elements = []
    for _ in range(8):
        sorted_elements.append(max_heap.extract().key)
    assert expected_sorted_elements == sorted_elements

    elements = [
        TreeNode(7, 7),
        TreeNode(25, 25),
        TreeNode(100, 100),
        TreeNode(1, 1),
        TreeNode(2, 2),
        TreeNode(3, 3),
        TreeNode(17, 17),
        TreeNode(19, 19),
        TreeNode(36, 36)
    ]
    min_heap = DHeap(elements=DynamicOneDimensionalArray(
        TreeNode, 9, elements),
                     heap_property="min")
    assert min_heap.extract().key == 1

    expected_sorted_elements = [2, 3, 7, 17, 19, 25, 36, 100]
    sorted_elements = [min_heap.extract().key for _ in range(8)]
    assert expected_sorted_elements == sorted_elements
def test_BinaryTreeTraversal():
    BST = BinarySearchTree
    BTT = BinaryTreeTraversal
    b = BST('F', 'F')
    b.insert('B', 'B')
    b.insert('A', 'A')
    b.insert('G', 'G')
    b.insert('D', 'D')
    b.insert('C', 'C')
    b.insert('E', 'E')
    b.insert('I', 'I')
    b.insert('H', 'H')
    trav = BTT(b)
    pre = trav.depth_first_search(order='pre_order')
    assert [str(n) for n in pre] == \
    ["(1, 'F', 'F', 3)", "(2, 'B', 'B', 4)", "(None, 'A', 'A', None)",
     "(5, 'D', 'D', 6)", "(None, 'C', 'C', None)", "(None, 'E', 'E', None)",
     "(None, 'G', 'G', 7)", "(8, 'I', 'I', None)", "(None, 'H', 'H', None)"]
    ino = trav.depth_first_search()
    assert [str(n) for n in ino] == \
    ["(None, 'A', 'A', None)", "(2, 'B', 'B', 4)", "(None, 'C', 'C', None)",
     "(5, 'D', 'D', 6)", "(None, 'E', 'E', None)", "(1, 'F', 'F', 3)",
     "(None, 'G', 'G', 7)", "(None, 'H', 'H', None)", "(8, 'I', 'I', None)"]
    out = trav.depth_first_search(order='out_order')
    assert [str(n) for n in out] == \
    ["(8, 'I', 'I', None)", "(None, 'H', 'H', None)", "(None, 'G', 'G', 7)",
     "(1, 'F', 'F', 3)", "(None, 'E', 'E', None)", "(5, 'D', 'D', 6)",
     "(None, 'C', 'C', None)", "(2, 'B', 'B', 4)", "(None, 'A', 'A', None)"]
    post = trav.depth_first_search(order='post_order')
    assert [str(n) for n in post] == \
    ["(None, 'A', 'A', None)", "(None, 'C', 'C', None)",
     "(None, 'E', 'E', None)", "(5, 'D', 'D', 6)", "(2, 'B', 'B', 4)",
     "(None, 'H', 'H', None)", "(8, 'I', 'I', None)", "(None, 'G', 'G', 7)",
     "(1, 'F', 'F', 3)"]
    bfs = trav.breadth_first_search()
    assert [str(n) for n in bfs] == \
        ["(1, 'F', 'F', 3)", "(2, 'B', 'B', 4)", "(None, 'G', 'G', 7)",
         "(None, 'A', 'A', None)", "(5, 'D', 'D', 6)", "(8, 'I', 'I', None)",
         "(None, 'C', 'C', None)", "(None, 'E', 'E', None)",
         "(None, 'H', 'H', None)"]
    assert raises(NotImplementedError,
                  lambda: trav.breadth_first_search(strategy='iddfs'))
    assert raises(NotImplementedError,
                  lambda: trav.depth_first_search(order='in_out_order'))
    assert raises(TypeError, lambda: BTT(1))
Example #20
0
def test_Queue():

    q1 = Queue(implementation='array', items=[0])
    q1.append(1)
    q1.append(2)
    q1.append(3)
    assert str(q1) == '[0, 1, 2, 3]'
    assert len(q1) == 4
    assert q1.popleft() == 0
    assert q1.popleft() == 1
    assert len(q1) == 2
    assert q1.popleft() == 2
    assert q1.popleft() == 3
    assert len(q1) == 0

    q1 = Queue()
    raises(ValueError, lambda: q1.popleft())

    q1 = Queue(implementation='linkedlist')
    q1.append(1)
    assert raises(TypeError, lambda: q1.append('a'))
    assert raises(TypeError, lambda: Queue(implementation='linkedlist', items=[0], dtype=str))
    assert raises(TypeError, lambda: Queue(implementation='linkedlist', items={0, 1}))
    q1 = Queue(implementation='linkedlist', items = [0, 1])
    q1.append(2)
    q1.append(3)
    assert str(q1) == '[0, 1, 2, 3]'
    assert len(q1) == 4
    assert q1.popleft().data == 0
    assert q1.popleft().data == 1
    assert len(q1) == 2
    assert q1.popleft().data == 2
    assert q1.popleft().data == 3
    assert len(q1) == 0
    raises(ValueError, lambda: q1.popleft())
def test_OneDimensionalSegmentTree():
    ODST = OneDimensionalSegmentTree
    segt = ODST([(0, 5), (1, 6), (9, 13), (1, 2), (3, 8), (9, 20)])
    assert segt.cache == False
    segt2 = ODST([(1, 4)])
    assert str(segt2) == (
        "[(None, [False, 0, 1, False], None, None), "
        "(None, [True, 1, 1, True], ['(None, [True, 1, 4, True], None, None)'], "
        "None), (None, [False, 1, 4, False], None, None), (None, [True, 4, 4, True], "
        "None, None), (0, [False, 0, 1, True], None, 1), (2, [False, 1, 4, True], "
        "['(None, [True, 1, 4, True], None, None)'], 3), (4, [False, 0, 4, True], "
        "None, 5), (None, [False, 4, 5, False], None, None), (-3, [False, 0, 5, "
        "False], None, -2)]")
    assert len(segt.query(1.5)) == 3
    assert segt.cache == True
    assert len(segt.query(-1)) == 0
    assert len(segt.query(2.8)) == 2
    raises(ValueError, lambda: ODST([(1, 2, 3)]))
Example #22
0
def test_Stack():

    s = Stack()
    s.push(1)
    s.push(2)
    s.push(3)
    assert s.peek == 3
    assert str(s) == '[1, 2, 3]'
    assert s.pop() == 3
    assert s.pop() == 2
    assert s.pop() == 1
    assert s.is_empty is True
    assert raises(IndexError, lambda : s.pop())
    _s = Stack(items=[1, 2, 3])
    assert str(_s) == '[1, 2, 3]'
    assert len(_s) == 3
    assert raises(NotImplementedError, lambda: Stack(implementation=''))

    s = Stack(implementation='linked_list')
    s.push(1)
    s.push(2)
    s.push(3)
    assert s.peek == 3
    assert str(s) == '[3, 2, 1]'
    assert s.pop().data == 3
    assert s.pop().data == 2
    assert s.pop().data == 1
    assert s.is_empty is True
    assert raises(IndexError, lambda : s.pop())
    _s = Stack(implementation='linked_list',items=[1, 2, 3])
    assert str(_s) == '[3, 2, 1]'
    assert len(_s) == 3

    s = Stack(implementation='linked_list',items=['a',None,type,{}])
    assert len(s) == 4
    assert s.size == 4

    top = s.top
    assert top.data == s.pop().data

    peek = s.peek
    assert peek == s.pop().data
    assert raises(TypeError, lambda: Stack(implementation='linked_list', items={0, 1}))
Example #23
0
def test_ImplementationPriorityQueue():
    impls = ['linked_list', 'binomial_heap', 'binary_heap']
    for impl in impls:
        pq1 = PriorityQueue(implementation=impl)
        pq1.push(1, 2)
        pq1.push(2, 3)
        pq1.push(3, 4)
        assert pq1.pop() == 1
        assert pq1.pop() == 2
        assert pq1.pop() == 3
        assert pq1.is_empty is True
        assert raises(IndexError, lambda: pq1.pop())
def test_adjacency_list():
    v_1 = AdjacencyListGraphNode('v_1', 1)
    v_2 = AdjacencyListGraphNode('v_2', 2)
    g = Graph(v_1, v_2, implementation='adjacency_list')
    v_3 = AdjacencyListGraphNode('v_3', 3)
    g.add_vertex(v_2)
    g.add_vertex(v_3)
    g.add_edge('v_1', 'v_2')
    g.add_edge('v_2', 'v_3')
    g.add_edge('v_3', 'v_1')
    assert g.is_adjacent('v_1', 'v_2') is True
    assert g.is_adjacent('v_2', 'v_3') is True
    assert g.is_adjacent('v_3', 'v_1') is True
    assert g.is_adjacent('v_2', 'v_1') is False
    assert g.is_adjacent('v_3', 'v_2') is False
    assert g.is_adjacent('v_1', 'v_3') is False
    neighbors = g.neighbors('v_1')
    assert neighbors == [v_2]
    v = AdjacencyListGraphNode('v', 4)
    g.add_vertex(v)
    g.add_edge('v_1', 'v', 0)
    g.add_edge('v_2', 'v', 0)
    g.add_edge('v_3', 'v', 0)
    assert g.is_adjacent('v_1', 'v') is True
    assert g.is_adjacent('v_2', 'v') is True
    assert g.is_adjacent('v_3', 'v') is True
    e1 = g.get_edge('v_1', 'v')
    e2 = g.get_edge('v_2', 'v')
    e3 = g.get_edge('v_3', 'v')
    assert (e1.source.name, e1.target.name) == ('v_1', 'v')
    assert (e2.source.name, e2.target.name) == ('v_2', 'v')
    assert (e3.source.name, e3.target.name) == ('v_3', 'v')
    g.remove_edge('v_1', 'v')
    assert g.is_adjacent('v_1', 'v') is False
    g.remove_vertex('v')
    assert g.is_adjacent('v_2', 'v') is False
    assert g.is_adjacent('v_3', 'v') is False

    assert raises(ValueError, lambda: g.add_edge('u', 'v'))
    assert raises(ValueError, lambda: g.add_edge('v', 'x'))
def test_DoublyLinkedList():
    random.seed(1000)
    dll = DoublyLinkedList()
    assert raises(IndexError, lambda: dll[2])
    dll.appendleft(5)
    dll.append(1)
    dll.appendleft(2)
    dll.append(3)
    dll.insert_after(dll[-1], 4)
    dll.insert_after(dll[2], 6)
    dll.insert_before(dll[4], 1.1)
    dll.insert_before(dll[0], 7)
    dll.insert_at(0, 2)
    dll.insert_at(-1, 9)
    dll.extract(2)
    assert dll.popleft().key == 2
    assert dll.popright().key == 4
    assert dll.search(3) == dll[-2]
    assert dll.search(-1) is None
    dll[-2].key = 0
    assert str(dll) == ("['(7, None)', '(5, None)', '(1, None)', "
                        "'(6, None)', '(1.1, None)', '(0, None)', "
                        "'(9, None)']")
    assert len(dll) == 7
    assert raises(IndexError, lambda: dll.insert_at(8, None))
    assert raises(IndexError, lambda: dll.extract(20))
    dll_copy = DoublyCircularLinkedList()
    for i in range(dll.size):
        dll_copy.append(dll[i])
    for i in range(len(dll)):
        if i % 2 == 0:
            dll.popleft()
        else:
            dll.popright()
    assert str(dll) == "[]"
    for _ in range(len(dll_copy)):
        index = random.randint(0, len(dll_copy) - 1)
        dll_copy.extract(index)
    assert str(dll_copy) == "[]"
    assert raises(ValueError, lambda: dll_copy.extract(1))
Example #26
0
def _test_RangeQueryStatic_common(func, gen_expected):

    array = OneDimensionalArray(int, [])
    raises(ValueError, lambda: RangeQueryStatic(array, func))

    array = OneDimensionalArray(int, [1])
    rq = RangeQueryStatic(array, func)
    assert rq.query(0, 0) == 1
    raises(ValueError, lambda: rq.query(0, -1))
    raises(IndexError, lambda: rq.query(0, 1))

    array_sizes = [3, 6, 12, 24, 48, 96]
    random.seed(0)
    for array_size in array_sizes:
        data = random.sample(range(-2 * array_size, 2 * array_size),
                             array_size)
        array = OneDimensionalArray(int, data)

        expected = []
        inputs = []
        for i in range(array_size):
            for j in range(i + 1, array_size):
                inputs.append((i, j))
                expected.append(gen_expected(data, i, j))

        data_structures = ["array", "sparse_table"]
        for ds in data_structures:
            rmq = RangeQueryStatic(array, func, data_structure=ds)
            for input, correct in zip(inputs, expected):
                assert rmq.query(input[0], input[1]) == correct
Example #27
0
def test_BinaryTreeTraversal():
    BST = BinarySearchTree
    BTT = BinaryTreeTraversal
    b = BST('F', 'F')
    b.insert('B', 'B')
    b.insert('A', 'A')
    b.insert('G', 'G')
    b.insert('D', 'D')
    b.insert('C', 'C')
    b.insert('E', 'E')
    b.insert('I', 'I')
    b.insert('H', 'H')
    trav = BTT(b)
    pre = trav.depth_first_search(order='pre_order')
    assert [node.key
            for node in pre] == ['F', 'B', 'A', 'D', 'C', 'E', 'G', 'I', 'H']

    ino = trav.depth_first_search()
    assert [node.key
            for node in ino] == ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

    out = trav.depth_first_search(order='out_order')
    assert [node.key
            for node in out] == ['I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']

    post = trav.depth_first_search(order='post_order')
    assert [node.key
            for node in post] == ['A', 'C', 'E', 'D', 'B', 'H', 'I', 'G', 'F']

    bfs = trav.breadth_first_search()
    assert [node.key
            for node in bfs] == ['F', 'B', 'G', 'A', 'D', 'I', 'C', 'E', 'H']

    assert raises(NotImplementedError,
                  lambda: trav.breadth_first_search(strategy='iddfs'))
    assert raises(NotImplementedError,
                  lambda: trav.depth_first_search(order='in_out_order'))
    assert raises(TypeError, lambda: BTT(1))
Example #28
0
def test_OneDimensionalArray():
    ODA = OneDimensionalArray
    A = ODA(int, 5, [1.0, 2, 3, 4, 5], init=6)
    A[1] = 2.0
    assert A
    assert ODA(int, [1.0, 2, 3, 4, 5], 5)
    assert ODA(int, 5)
    assert ODA(int, [1.0, 2, 3])
    assert raises(IndexError, lambda: A[7])
    assert raises(IndexError, lambda: A[-1])
    assert raises(ValueError, lambda: ODA())
    assert raises(ValueError, lambda: ODA(int, 1, 2, 3))
    assert raises(TypeError, lambda: ODA(int, 5.0, set([1, 2, 3])))
    assert raises(TypeError, lambda: ODA(int, 5.0))
    assert raises(TypeError, lambda: ODA(int, set([1, 2, 3])))
    assert raises(ValueError, lambda: ODA(int, 3, [1]))
Example #29
0
def test_AdjacencyListGraphNode():
    g_1 = AdjacencyListGraphNode('g_1', 1)
    g_2 = AdjacencyListGraphNode('g_2', 2)
    g = AdjacencyListGraphNode('g', 0, adjacency_list=[g_1, g_2])
    g.add_adjacent_node('g_3', 3)
    assert g.g_1.name == 'g_1'
    assert g.g_2.name == 'g_2'
    assert g.g_3.name == 'g_3'
    g.remove_adjacent_node('g_3')
    assert hasattr(g, 'g_3') is False
    assert raises(ValueError, lambda: g.remove_adjacent_node('g_3'))
    g.add_adjacent_node('g_1', 4)
    assert g.g_1.data == 4
    assert str(g) == "('g', 0)"
def test_DoublyCircularLinkedList():
    random.seed(1000)
    dcll = DoublyCircularLinkedList()
    assert raises(IndexError, lambda: dcll[2])
    dcll.appendleft(5)
    dcll.append(1)
    dcll.appendleft(2)
    dcll.append(3)
    dcll.insert_after(dcll[-1], 4)
    dcll.insert_after(dcll[2], 6)
    dcll.insert_before(dcll[4], 1)
    dcll.insert_before(dcll[0], 7)
    dcll.insert_at(0, 2)
    dcll.insert_at(-1, 9)
    dcll.extract(2)
    assert dcll.popleft().key == 2
    assert dcll.popright().key == 4
    dcll[-2].key = 0
    assert str(dcll) == "['7', '5', '1', '6', '1', '0', '9']"
    assert len(dcll) == 7
    assert raises(IndexError, lambda: dcll.insert_at(8, None))
    assert raises(IndexError, lambda: dcll.extract(20))
    dcll_copy = DoublyCircularLinkedList()
    for i in range(dcll.size):
        dcll_copy.append(dcll[i])
    for i in range(len(dcll)):
        if i % 2 == 0:
            dcll.popleft()
        else:
            dcll.popright()
    assert str(dcll) == "[]"
    for _ in range(len(dcll_copy)):
        index = random.randint(0, len(dcll_copy) - 1)
        dcll_copy.extract(index)
    assert str(dcll_copy) == "[]"
    assert raises(ValueError, lambda: dcll_copy.extract(1))