Ejemplo n.º 1
0
class BSTtreeDict(BST):
    '''A BST-based implementation of a sorted dictionary'''
    def __init__(self):
       
        self._items = BST()
    
    def __getitem__(self,key):	
    	'''Returns the value associated with key or returns None if key does not exist.'''
        return self._items.find(key)

    def __setitem__(self, key, value):
    	self._items.add((key, value))
           
    def __contains__(self,key): 
        return self.__getitem__(key) != None

    def __str__(self):
        return str(self._items) 

    def __len__(self): 
        return len(self._items)   

    def __iter__(self): 
        return iter(self._items)

    def pop(self,key): 
        return self._items.remove(key) 
Ejemplo n.º 2
0
def medium_depth():
    """a bst with several levels of depth"""
    x = [10, 5, 3, 7, 2, 4, 6, 8, 15, 12, 11, 13, 17, 16, 18]
    bst = BST()
    for i in x:
        bst.insert(i)
    return bst
def test_medium_tree():
    """returns medium tree""" 
    l = [10, 5, 15, 3, 6, 14, 16]
    tree = BST()
    for i in l:
        tree.insert(i)  
    return tree
Ejemplo n.º 4
0
    def setUp(self):
        self.bst = BST()
        self.node_5 = Node(-5)
        self.node_4 = Node(-4)
        self.node_3 = Node(-3)
        self.node_2 = Node(-2)
        self.node_1 = Node(-1)
        self.node0 = Node(0)
        self.node1 = Node(1)
        self.node2 = Node(2)
        self.node3 = Node(3)
        self.node4 = Node(4)
        self.node5 = Node(5)

        self.mytree = BST()
        self.mytree.insert(5)
        self.mytree.insert(2)
        self.mytree.insert(3)
        self.mytree.insert(1)
        self.mytree.insert(4)
        self.mytree.insert(0)
        self.mytree.insert(2.5)
        self.mytree.insert(8)
        self.mytree.insert(9)
        self.mytree.insert(6)
        self.mytree.insert(4.5)
def test_large_tree():
    """returns large tree"""
    l = [10, 5, 15, 9, 3, 4567, 55, 6, 1, 12334, 14, 16, 77, 24, 9]
    tree = BST()
    for i in l:
        tree.insert(i)  
    return tree
Ejemplo n.º 6
0
def test_delete_head_only():
    """Test deleteing a one node head."""
    from bst import BST
    b = BST([20])
    assert b.contains(20) is True
    b.delete(20)
    assert b.contains(20) is False
Ejemplo n.º 7
0
def short_depth():
    """a small bst with a depth of 2"""
    x = [10, 3, 15, 4]
    bst = BST()
    for i in x:
        bst.insert(i)
    return bst
Ejemplo n.º 8
0
def test_insert_same():
    """Test that a value cannot be added to tree if it already exisits."""
    from bst import BST
    new_bst = BST()
    new_bst.insert(5)
    with pytest.raises(ValueError):
        new_bst.insert(5)
Ejemplo n.º 9
0
def test_contains():
    bst = BST()
    for i in range(1,11):
        bst.insert(i)
    assert bst.contains(1)
    assert bst.contains(5)
    assert not bst.contains(15)
Ejemplo n.º 10
0
def test_building_to_fanciest01():
    """Everything works up to inserting 200."""
    from bst import BST
    b = BST()
    b.insert(100)
    b.insert(70)
    b.insert(80)
    b.insert(53)
    b.insert(60)
    b.insert(200)
    assert b.root.value == 80
    assert b.root.left_depth == 2
    assert b.root.right_depth == 2

    assert b.root.left.value == 60
    assert b.root.left.left_depth == 1
    assert b.root.left.right_depth == 1

    assert b.root.left.left.value == 53
    assert b.root.left.left.left_depth == 0
    assert b.root.left.left.right_depth == 0

    assert b.root.left.right.value == 70
    assert b.root.left.right.left_depth == 0
    assert b.root.left.right.right_depth == 0

    assert b.root.right.value == 100
    assert b.root.right.left_depth == 0
    assert b.root.right.right_depth == 1

    assert b.root.right.right.value == 200
    assert b.root.right.right.left_depth == 0
    assert b.root.right.right.right_depth == 0
Ejemplo n.º 11
0
def test_insert_two_nodes_one_return_root(empty_tree):
    """Test insert places lesser node to node root left."""
    from bst import BST
    bst = BST()
    bst.insert(50)
    bst.insert(45)
    assert bst.root.val == 50
Ejemplo n.º 12
0
def test_node_left_and_right_attributes_change():
    """Test that left and right node attributes are added with insert."""
    b = BST([5])
    b.insert(4)
    b.insert(6)
    assert b.root.left.val == 4
    assert b.root.right.val == 6
Ejemplo n.º 13
0
def test_insert_value_into_emtpy_bst_creates_root_node_with_value_inerted():
    """Test that inserting value into empty bst creates root node."""
    from bst import BST
    t = BST()
    t.insert(5)
    assert t.root
    assert t.root.value == 5
Ejemplo n.º 14
0
def test_insert_value_less_than_root_value_creates_left_node_child():
    """Test inserting value less than root value creates left child node of root."""
    from bst import BST
    t = BST([5])
    t.insert(4)
    assert t.root.left.value == 4
    assert t.root.right is None
Ejemplo n.º 15
0
def main():
    tree = BST()
    N = 11
    _set = set([random.randint(1, N * N) for _ in range(N)])
    for x in _set:
        tree.insert(x, "")

    print "original tree"
    tree.pretty_print()

    inorder = [node.key for node in tree.inorder_nodes()]
    preorder = [node.key for node in tree.preorder_nodes()]

    # now build a new tree from these traversals
    root = binary_tree_from_traversals(preorder, inorder)
    new_tree = BST()
    new_tree.root = root
    print "reconstructed tree"
    new_tree.pretty_print()

    # verify the correctness
    for orig_node, cloned_node in zip(tree.levelorder_nodes(),
                                      new_tree.levelorder_nodes()):
        assert orig_node is not cloned_node
        assert orig_node.key == cloned_node.key
def long_depth():
    """a bst with several levels of depth"""
    x = [6, 5, 7, 7, 2, 4, 6, 8, 16, 12, 10, 13, 17, 17, 6]
    bst = BST()
    for i in x:
        bst.insert(i)
    return bst
Ejemplo n.º 17
0
def main():
    tree = BST()
    tree.read_File('input.txt')
    tree.print_tree()
    tree.delete(19)
    print('')
    tree.print_tree()
Ejemplo n.º 18
0
    def test_count_root(self):
        root = BSTNode(10, 10, None)
        tree = BST(root)
        node = BSTNode(15, 10, None)
        tree.AddKeyValue(15, 10)

        self.assertEqual(tree.Count(), 2)
Ejemplo n.º 19
0
def test_depth():
    aBST = BST()
    assert aBST.depth() == 0
    for num, depth in zip([4, 2, 6, 3, 7, 8, 9, 10, 11],
                          [1, 2, 2, 3, 3, 4, 5,  6,  7]):
        aBST.insert(num)
        assert aBST.depth() == depth
Ejemplo n.º 20
0
def test_balance():
    aBST = BST()
    assert aBST.balance() == 0
    for num, bal in zip([4, 2, 6, 3, 7, 8, 9, 10, 11],
                        [0, 1, 0, 1, 0, -1, -2, -3]):
        aBST.insert(num)
        assert aBST.balance() == bal
Ejemplo n.º 21
0
def test_valid():
    print('{}'.format('-' * 20))
    print('Testing BST.valid:\n')

    bst = BST()
    print('bst = {}'.format(bst.inorder()))
    print('bst.valid() = {}'.format(bst.is_valid()))
    print()

    bst = get_bst()
    print('bst = {}'.format(bst.inorder()))
    print('bst.valid() = {}'.format(bst.is_valid()))
    print()

    print('change bst property (change 19 to 29):')
    bst._root._left._right._data = 29
    print('bst = {}'.format(bst.inorder()))
    print('bst.valid() = {}'.format(bst.is_valid()))
    print()

    print('change bst property (change 38 to 48):')
    bst._root._left._right._data = 19
    bst._root._right._right._left._data = 48
    print('bst = {}'.format(bst.inorder()))
    print('bst.valid() = {}'.format(bst.is_valid()))
    print()

    print('End of BST.valid testing')
    print('{}\n'.format('-' * 20))
    return
def check_intersection(hull1, hull2):
    bstX_h1 = BST()
    bstY_h1 = BST()

    maxX_h2 = float('-inf')
    minX_h2 = float('inf')
    maxY_h2 = float('-inf')
    minY_h2 = float('inf')
    ptArray = hull1.points
    ptArray2 = hull2.points
    for vertex in hull1.vertices:
        # print (ptArray[vertex])
        bstX_h1.insert(ptArray[vertex][0])
        bstY_h1.insert(ptArray[vertex][1])
    for vertex in hull2.vertices:
        maxX_h2 = max(maxX_h2, ptArray2[vertex][0])
        minX_h2 = min(minX_h2, ptArray2[vertex][0])
        maxY_h2 = max(maxY_h2, ptArray2[vertex][1])
        minY_h2 = min(minY_h2, ptArray2[vertex][1])

    len_x = functools.reduce(lambda x, y: x + 1,
                             bstX_h1.range(minX_h2, maxX_h2), 0)
    len_y = functools.reduce(lambda x, y: x + 1,
                             bstY_h1.range(minY_h2, maxY_h2), 0)
    return len_x > 0 and len_y > 0
Ejemplo n.º 23
0
def test_delete_2_works_on_node_with_one_right_child_left_side():
    """Test the delete_2 method deletes a node with a right child."""
    from bst import BST
    tree = BST([10, 6, 8, 9, 12, 16, 14])
    tree.delete_2(6)
    in_order_gen = tree.in_order()
    assert [n for n in in_order_gen] == [8, 9, 10, 12, 14, 16]
Ejemplo n.º 24
0
def test_insert_value_grater_than_root_creates_right_node_child():
    """Test inserting value grater than root value creates right childe node of root."""
    from bst import BST
    t = BST([5])
    t.insert(7)
    assert t.root.right.value == 7
    assert t.root.left is None
Ejemplo n.º 25
0
def test_child_setting():
    """Test that inserting a value less than
    head sets right child value to head."""
    from bst import BST
    new_bst = BST()
    new_bst.insert(5)
    new_bst.insert(3)
    assert new_bst.head.get_left_child().data == 3
Ejemplo n.º 26
0
 def test_insert(self):
     bst = BST()
     self.assertTrue(bst.insert(5))
     self.assertTrue(bst.insert(10))
     self.assertTrue(bst.insert(1))
     self.assertFalse(bst.insert(5))
     self.assertTrue(bst.root.left is not None)
     self.assertTrue(bst.root.right is not None)
Ejemplo n.º 27
0
def test_ordered_with_floats():
    """Test floats are returned properly."""
    a = BST([1.8, 1.4, 1.9, 1.2])
    b = a.ordered()
    assert next(b) == 1.2
    assert next(b) == 1.4
    assert next(b) == 1.8
    assert next(b) == 1.9
Ejemplo n.º 28
0
def tree_sort(self):
    tree = BST()
    if self is []:
        return []
    for i in range(len(self)):
        tree.insert(self[i])
    items = tree.inorder2()
    return items
 def test_delete_case_1(self):
     print("Running test_delete_case_1")
     h = BST([50, 30, 70, 20, 40, 60, 80])
     h.delete(20)
     self.check_multiline(str(h),
                          [["50"], ["30", "70"], ["_", "40", "60", "80"],
                           ["_", "_", "_", "_", "_", "_"],
                           ["30", "40", "50", "60", "70", "80"]])
Ejemplo n.º 30
0
def test_bst_can_take_string_at_initialization():
    """Test that the BST can take a string."""
    from bst import BST
    b = BST('abc')
    assert b.size() == 3
    assert b.depth() == 2
    assert b.left_depth == 0
    assert b.right_depth == 2
Ejemplo n.º 31
0
def tiny_tree():
    from bst import BST
    new_bst = BST()
    new_bst.insert(30)
    new_bst.insert(50)
    new_bst.insert(75)

    return new_bst
Ejemplo n.º 32
0
def test_post_order_sample_tree():
    """Check for the correct output of posto-t on a sample tree."""
    tree = BST(SAMPLE_TREE)
    gen = tree.post_order()
    output = []
    for i in range(10):
        output.append(next(gen))
    assert output == [1, 11, 10, 16, 12, 27, 28, 42, 30, 20]
Ejemplo n.º 33
0
def test_breadth_first_sample_tree():
    """Check for the correct output of bft on a right-imbalanced tree."""
    tree = BST(SAMPLE_TREE)
    gen = tree.breadth_first()
    output = []
    for i in range(10):
        output.append(next(gen))
    assert output == [20, 12, 30, 10, 16, 28, 42, 1, 11, 27]
Ejemplo n.º 34
0
def test_post_order_right_imba():
    """Check for the correct output of posto-t on a right-imbalanced tree."""
    tree = BST(RIGHT_IMBALANCED)
    gen = tree.post_order()
    output = []
    for i in range(6):
        output.append(next(gen))
    assert output == [6, 5, 4, 3, 2, 1]
Ejemplo n.º 35
0
def test_breadth_first_right_imba():
    """Check for the correct output of bft on a right-imbalanced tree."""
    tree = BST(RIGHT_IMBALANCED)
    gen = tree.breadth_first()
    output = []
    for i in range(6):
        output.append(next(gen))
    assert output == [1, 2, 3, 4, 5, 6]
Ejemplo n.º 36
0
def test_breadth_first_left_imba():
    """Check for the correct output of bft on a left-imbalanced tree."""
    tree = BST(LEFT_IMBALANCED)
    gen = tree.breadth_first()
    output = []
    for i in range(6):
        output.append(next(gen))
    assert output == [6, 5, 4, 3, 2, 1]
Ejemplo n.º 37
0
def test_bst_can_take_tuple_at_initialization():
    """Test that the BST can take a tuple."""
    from bst import BST
    b = BST((1, 2, 3))
    assert b.size() == 3
    assert b.depth() == 2
    assert b.left_depth == 0
    assert b.right_depth == 2
Ejemplo n.º 38
0
def test_larger_child():
    """Test that inserting a value greater than
    head sets the left child of head."""
    from bst import BST
    new_bst = BST()
    new_bst.insert(5)
    new_bst.insert(9)
    assert new_bst.head.get_right_child().data == 9
Ejemplo n.º 39
0
def test_post_order_left_imba():
    """Check for the correct output of posto-t on a left-imbalanced tree."""
    tree = BST(LEFT_IMBALANCED)
    gen = tree.post_order()
    output = []
    for i in range(6):
        output.append(next(gen))
    assert output == [1, 2, 3, 4, 5, 6]
Ejemplo n.º 40
0
def test_pre_order_solo():
    """Test running pre-order on a tree with one Node."""
    from bst import BST
    b = BST([132])
    pre_ord = b.pre_order()
    pre_ord_list = []
    for ii in pre_ord:
        pre_ord_list.append(ii)
    assert pre_ord_list == [132]
Ejemplo n.º 41
0
def test_post_order_empty():
    """Test an empty Node returns empty list."""
    from bst import BST
    b = BST()
    post_ord = b.post_order()
    post_ord_list = []
    for ii in post_ord:
        post_ord_list.append(ii)
    assert post_ord_list == []
Ejemplo n.º 42
0
def test_post_order_solo():
    """Test running post-order on a tree with one Node."""
    from bst import BST
    b = BST([35])
    post_ord = b.post_order()
    post_ord_list = []
    for ii in post_ord:
        post_ord_list.append(ii)
    assert post_ord_list == [35]
Ejemplo n.º 43
0
def test_breath_first_empty():
    """Test an empty Node returns empty list."""
    from bst import BST
    b = BST()
    breath = b.breath_first()
    breath_first_list = []
    for ii in breath:
        breath_first_list.append(ii)
    assert breath_first_list == []
Ejemplo n.º 44
0
def test_breath_first_solo():
    """Test running breath on a tree with one Node."""
    from bst import BST
    b = BST([25])
    breath = b.breath_first()
    breath_first_list = []
    for ii in breath:
        breath_first_list.append(ii)
    assert breath_first_list == [25]
Ejemplo n.º 45
0
def test_in_order_solo():
    """Test running in-order on a tree with one Node."""
    from bst import BST
    b = BST([20])
    in_ord = b.in_order()
    in_ord_list = []
    for ii in in_ord:
        in_ord_list.append(ii)
    assert in_ord_list == [20]
Ejemplo n.º 46
0
def test_inorder():
    nums = range(1, 200)
    random.shuffle(nums)
    bst = BST()
    for n in nums:
        bst.add(n)
    nums.sort()

    assert bst.inorder() == sorted(nums)
Ejemplo n.º 47
0
 def grade(self, array):
     bst = BST()
     for i in array:
         bst.add(i)
     array = sorted(array)
     ptr = 0
     for i in bst:
         self.assertEqual(i, array[ptr])
         ptr += 1
Ejemplo n.º 48
0
def test_in_order_empty():
    """Test an empty Node returns empty list."""
    from bst import BST
    b = BST()
    in_ord = b.in_order()
    in_ord_list = []
    for ii in in_ord:
        in_ord_list.append(ii)
    assert in_ord_list == []
Ejemplo n.º 49
0
    def test_insert_2(self):
        # Arrange + Act
        b = BST(1)
        b.insert(3)
        b.insert(2)

        # Assert
        self._check_node(b, 1, None, 3)
        self._check_node(b.right, 3, 2, None)
        self._check_node(b.right.left, 2, None, None)
Ejemplo n.º 50
0
    def test_insert_5(self):
        # Arrange + Act
        b = BST(3)
        b.insert(1)
        b.insert(2)

        # Assert
        self._check_node(b, 3, 1, None)
        self._check_node(b.left, 1, None, 2)
        self._check_node(b.left.right, 2, None, None)
Ejemplo n.º 51
0
    def test_insert_4(self):
        # Arrange + Act
        b = BST(2)
        b.insert(3)
        b.insert(1)

        # Assert
        self._check_node(b, 2, 1, 3)
        self._check_node(b.left, 1, None, None)
        self._check_node(b.right, 3, None, None)
Ejemplo n.º 52
0
 def test_preorder(self):
     bst = BST()
     bst.insert(5)
     bst.insert(10)
     bst.insert(1)
     bst.insert(3)
     bst.insert(59)
     preorder = bst.get_preorder()
     expected = [1, 3, 5, 10, 59]
     self.assertEqual(preorder, expected)
Ejemplo n.º 53
0
    def test_insert_6(self):
        # Arrange + Act
        b = BST(3)
        b.insert(2)
        b.insert(1)

        # Assert
        self._check_node(b, 3, 2, None)
        self._check_node(b.left, 2, 1, None)
        self._check_node(b.left.left, 1, None, None)
Ejemplo n.º 54
0
 def test_inorder(self):
     bst = BST()
     bst.insert(5)
     bst.insert(10)
     bst.insert(1)
     bst.insert(3)
     bst.insert(59)
     inorder = bst.get_inorder()
     expected = [5, 1, 3, 10, 59]
     self.assertEqual(inorder, expected)
Ejemplo n.º 55
0
 def test_postorder(self):
     bst = BST()
     bst.insert(5)
     bst.insert(10)
     bst.insert(1)
     bst.insert(3)
     bst.insert(59)
     postorder = bst.get_postorder()
     expected = [3, 1, 59, 10, 5]
     self.assertEqual(postorder, expected)
Ejemplo n.º 56
0
def test_size():
    aBST = BST()
    assert aBST.size == 0
    for num, size in zip([6, 2, 8, 4, 1000, -111],
                         [1, 2, 3, 4, 5, 6]):
        aBST.insert(num)
        assert aBST.size == size
    for x in range(2000):
        aBST.insert(uuid4())
    assert aBST.size == 2006
Ejemplo n.º 57
0
def test_depth_collatz():
    bst = BST()
    for i in range(1,11):
        if not i % 2:
            i /= 2
        else:
            i = i * 3 + 1
        print('i = {}'.format(i))
        bst.insert(i)
    assert bst.depth(bst.root) == 5
Ejemplo n.º 58
0
def bstsort(l):
    arbol = BST()
    # Generamos nuestra estructura 
    # de datos auxiliar
    
    while l:
        # Vaciamos la lista en el arbol
        item = l.pop()
        arbol.add(item)
    
    l.extend(arbol.inorder())
Ejemplo n.º 59
0
def filled_tree():
    A = Node(6)
    a = BST()
    a.root = A
    A.left = 4
    A.right = 7
    A.left.left = 3
    A.left.right = 5
    A.right.right = 8
    a._size = 6
    return a
Ejemplo n.º 60
0
def test_depth():
    bst = BST()
    bst.insert(5)
    assert bst.depth(node=bst.root) == 1
    bst.insert(3)
    bst.insert(4)
    bst.insert(6)
    assert bst.depth(node=bst.root) == 3