Ejemplo n.º 1
0
def test_delete_one_item():
    from bst import BST
    bst = BST()
    bst.insert(42)
    bst.delete(42)
    assert not bst._search(42)
    assert not bst.contains(42)
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
Ejemplo n.º 3
0
def test_delete_no_children():
    """delete(self, val) should remove val from the tree if present,
    if not present it should do nothing. Return None in all cases"""
    bintree = BST()
    with pytest.raises(TypeError):
        bintree.delete()  # 1 value required

    bintree.insert(5)
    bintree.insert(3)
    bintree.insert(7)
    bintree.insert(2)
    bintree.insert(4)
    bintree.insert(1)
    bintree.insert(9)
    bintree.insert(10)
    #     5
    #    / \
    #   3   7
    #  /\    \
    # 2  4    9
    # |       |
    # 1       10
    assert bintree.size() == 8
    assert bintree.delete(-1) is None
    assert bintree.size() == 8
    assert bintree.delete(4) is None
    assert bintree.size() == 7
    assert not bintree.leftchild.rightchild  # 4 is gone
    assert bintree.delete(10) is None
    assert bintree.size() == 6
    assert not bintree.rightchild.rightchild.leftchild  # 9 is a leaf
    assert not bintree.rightchild.rightchild.rightchild
Ejemplo n.º 4
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
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_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
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.º 8
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.º 9
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.º 10
0
def basic_setup():
    """A basic setup with two numbers."""
    from bst import BST
    b = BST()
    b.insert(9)
    b.insert(10)
    return b
Ejemplo n.º 11
0
def test_right_balance():
    bst = BST()
    bst.insert(5)
    bst.insert(6)
    bst.insert(7)
    bst.insert(3)
    assert bst.balance() == -1
Ejemplo n.º 12
0
class PhoneBook:

    def __init__(self):
        self.__phonebook = BST()

    def insert(self, number, name):
        entry = self.__phonebook.lookup(name)
        if entry is None:
            self.__phonebook.insert(name, [number])
        else:
            value = entry.get_value()
            value.append(number)

    def lookup(self, name):
        entry = self.__phonebook.lookup(name)
        if entry is not None:
            print('{}: [{}]'.format(entry.get_key(), entry.get_value()))
        else:
            print("NOT FOUND!")

    def list(self):
        all_entries = self.__phonebook.traverse(1)
        for e in all_entries:
            print('{}: [{}]'.format(e[0], ', '.join(e[1])))

    def remove(self, name):
        self.__phonebook.remove(name)
Ejemplo n.º 13
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.º 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 test_size():
    bst = BST()
    assert bst.size() == 0
    bst.insert(5)
    assert bst.size() == 1
    bst.insert(5)
    assert bst.size() == 1
Ejemplo n.º 16
0
def test_right_balance():
    bst = BST()
    bst.insert(5)
    bst.insert(6)
    bst.insert(7)
    bst.insert(3)
    assert bst.balance() == -1
Ejemplo n.º 17
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)
 def test_insert_single_node(self):
     print("Running test_insert_single_node")
     h = BST()
     h.insert(5)
     self.assertEqual(h.get_root().get_key(), 5)
     self.assertEqual(str(h.get_root()), '5')
     self.check_multiline(str(h), [["5"], ["_", "_"], ["5"]])
Ejemplo n.º 19
0
def test_left_balance():
    bst = BST()
    bst.insert(5)
    bst.insert(4)
    bst.insert(3)
    bst.insert(6)
    assert bst.balance() == 1
Ejemplo n.º 20
0
def test_left_balance():
    bst = BST()
    bst.insert(5)
    bst.insert(4)
    bst.insert(3)
    bst.insert(6)
    assert bst.balance() == 1
Ejemplo n.º 21
0
    def test_removal(self):
        bst = BST()
        bst.insert(5)
        bst.insert(10)
        bst.insert(1)
        bst.insert(3)
        bst.insert(59)

        # remove leaf node
        bst.remove(3)
        inorder = bst.get_inorder()
        self.assertEqual(inorder, [5, 1, 10, 59])
        self.assertEqual(bst.size, 4)

        # remove node with one child
        bst.remove(10)
        inorder = bst.get_inorder()
        self.assertEqual(inorder, [5, 1, 59])
        self.assertEqual(bst.size, 3)

        bst.insert(3)
        bst.insert(4)

        bst.remove(5)
        inorder = bst.get_inorder()
        self.assertEqual(inorder, [4, 1, 3, 59])
        self.assertEqual(bst.size, 4)
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.º 23
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.º 24
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.º 25
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.º 26
0
def test_rebalance():
    """Tests my rebalancing algorithm"""
    bintree = BST()

    for i in xrange(100):
        bintree.insert(random.randint(0, 1e6))
    assert bintree.size() == 100

    original_depth = bintree.depth()

    bintree.rebalance()
    assert abs(bintree.balance()) < 2
    assert original_depth > bintree.depth()

    bintree = BST()

    for i in xrange(100):
        bintree.insert(i)  # Horribly unbalanced
    assert bintree.size() == 100
    assert bintree.depth() == 100
    assert bintree.balance() == -99

    bintree.rebalance()
    assert abs(bintree.balance()) < 2
    assert bintree.depth() < 10  # Much better, anyway
 def testFindMin(self):
     tree2 = BST()
     self.assertIsNone(tree2.find_min())
     tree2.insert(5)
     self.assertEqual(5, tree2.find(5).key)
     self.assertEqual(5, tree2.find_min().key)
     self.assertEqual(4, self.tree1.find_min().key)
Ejemplo n.º 28
0
class PhoneBook():
    def __init__(self):
        self.tree = BST(None, compare)

#inserts a new contact
    def insert(self, number, name):
        found = self.tree.lookup(lambda x: x["value"]["name"] is name)
        if found is not None:
            found["value"]["number"] = number
        else:
            self.tree.insert({
                "name": name,
                "number": number
            })

#lookup a name and print its phone number
    def lookup(self, name):
        return self.tree.lookup(lambda x: x["value"]["name"] is name)

#list all records in an alphabetical order
    def list(self):
        result = []
        self.tree.traverse(lambda x: result.append(x["value"]))
        return result

#remove a record for a given name
    def remove(name):
        pass
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.º 30
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.º 31
0
def test_size():
    bst = BST()
    assert bst.size() == 0
    bst.insert(5)
    assert bst.size() == 1
    bst.insert(5)
    assert bst.size() == 1
Ejemplo n.º 32
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.º 33
0
 def test_inorder_predecessor(self):
     bst = BST()
     bst.insert(5)
     bst.insert(1)
     bst.insert(2)
     bst.insert(3)
     n = bst._get_next_inorder_predecessor(bst.root)
     self.assertEqual(n.val, 3)
Ejemplo n.º 34
0
def test_right_rotate():
    '''checks right_rotate balances the BTS'''
    bst = BST()
    bst.insert(20)
    bst.insert(10)
    bst.insert(5)
    balance = bst.balance()
    assert balance == 0
Ejemplo n.º 35
0
def test_make_balanced_randomly():
    aBST = BST()
    for y in range(300):
        for x in range(1000):
            aBST.insert(randint(0, 1000))
        aBST.make_balanced()
        b = aBST.balance()
        assert b in [1, 0, -1]
Ejemplo n.º 36
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
Ejemplo n.º 37
0
def test_contains_returns_false_if_value_not_in_bst(val):
    """Test contains returns false if value is not in the tree."""
    from bst import BST
    t = BST()
    t.insert(3)
    t.insert(1)
    t.insert(5)
    assert t.contains(23) is False
 def testDelateLastNode(self):
     tree2 = BST()
     tree2.insert(1)
     deleted = tree2.delete(1)
     self.assertEqual(1, deleted.key)
     tree2.check_ri()
     tree2.insert(2)
     tree2.check_ri()
Ejemplo n.º 39
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.º 40
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.º 41
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.º 42
0
def get_bst(items):
    '''Return a BST with elements from items, inserted in order starting
    with an empty tree.

    '''
    bst = BST()
    for item in items:
        bst.insert(item)
    return bst
Ejemplo n.º 43
0
def test_delete_head_one_right_child():
    """Test deleting a head with one right child."""
    from bst import BST
    b = BST([20])
    b.insert(22)
    assert b.contains(20) is True
    b.delete(20)
    assert b.contains(20) is False
    assert b.top.value == 22
Ejemplo n.º 44
0
def test_size_goes_up_with_each_value_inserted_to_bst():
    """Test that size increases by one with every value inserted."""
    from bst import BST
    t = BST()
    t.insert(4)
    t.insert(3)
    t.insert(5)
    t.insert(7)
    assert t.size() == 4
Ejemplo n.º 45
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.º 46
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.º 47
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.º 48
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.º 49
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.º 50
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.º 51
0
def test_contains2():
    root = Node(10)
    bst = BST(root)
    bst.insert(5)
    bst.insert(15)
    bst.insert(20)
    bst.insert(0)
    bst.insert(-5)
    bst.insert(3)
    assert bst.contains(1) == False
Ejemplo n.º 52
0
def test_contains4():
    root = Node(10)
    bst = BST(root)
    bst.insert(5)
    bst.insert(15)
    bst.insert(20)
    bst.insert(0)
    bst.insert(-5)
    bst.insert(3)
    assert bst.contains(0) == True
Ejemplo n.º 53
0
def test_insert2():
    root = Node(10)
    bst = BST(root)
    bst.insert(5)
    bst.insert(15)
    bst.insert(20)
    bst.insert(0)
    bst.insert(-5)
    bst.insert(3)
    assert bst.root.left.left.right.data == 3
Ejemplo n.º 54
0
def test_insert1():
    root = Node(10)
    bst = BST(root)
    bst.insert(5)
    bst.insert(15)
    bst.insert(17)
    assert bst.root.data == 10
    assert bst.root.left.data == 5
    assert bst.root.right.data == 15
    assert bst.root.right.right.data == 17
Ejemplo n.º 55
0
def test_depth():
    tree = BST()
    assert tree.depth() == 0
    items = [0, -2, -1, -4, -3]
    for item in items:
        tree.insert(item)
    assert tree.depth() == 4
    items = [1, 2, 3, 4]
    for item in items:
        tree.insert(item)
    assert tree.depth() == 5
Ejemplo n.º 56
0
def test_balance():
    tree = BST()
    assert tree.balance() == 0
    items = [0, -2, -1, -4, -3]
    for item in items:
        tree.insert(item)
    assert tree.balance() == 3
    items = [1, 2, 3, 4]
    for item in items:
        tree.insert(item)
    assert tree.balance() == -1
Ejemplo n.º 57
0
def test_delete_head_two_children():
    """Test deleting a head with two children."""
    from bst import BST
    b = BST([20])
    b.insert(18)
    b.insert(22)
    assert b.contains(20) is True
    b.delete(20)
    assert b.contains(20) is False
    assert b.top.value == 22
    assert b.top.left.value == 18
    assert b.top.right is None
Ejemplo n.º 58
0
def test_lr_levels():
    aBST = BST()
    assert aBST._lr_levels() == None
    for num, level in zip([4, 2, 6, 1, 3, 5, 7],
                          [(0, 0), (1, 0), (1, 1),
                          (2, 1), (2, 1), (2, 2), (2, 2)]):
        aBST.insert(num)
        assert aBST._lr_levels() == level
    aBST = BST()
    for x in range(20):
        aBST.insert(x)
    assert aBST._lr_levels() == (0, 19)