Пример #1
0
def bst_construct(
        data,
        key_column_index):  # construct a bst using LoL data and a index key
    tree = bst.BinarySearchTree()  # create the tree
    for element in data:  # add each element of data to tree
        tree[element[key_column_index]] = element
    return tree
Пример #2
0
    def test_delete_rebalance_two_children(self):
        #          20
        #         /  \
        #        15   25
        #       /     /\
        #      10    24 26
        #                \
        #                 27
        vals = [20, 15, 25, 10, 26, 24, 27]
        test_bst = bst.BinarySearchTree()
        for val in vals:
            test_bst.insert(val)
        test_bst.delete(25)
        #          20
        #         /  \
        #        15   24
        #       /      \
        #      10      26
        #                \
        #                 27
        # ==>
        #          20
        #         /  \
        #        15   26
        #       /     / \
        #      10     24 27

        self.assertEquals(26, test_bst.right.value)
Пример #3
0
def test_set_up_tree_with_iterables(data, result):
    """Test if tree properly loads with different iterables given as arguements."""
    test_tree = bst.BinarySearchTree(data)
    test_array = []
    test_generator = test_tree.in_order()
    while len(test_array) < test_tree.size():
        test_array.append(next(test_generator))
    assert test_array == result
Пример #4
0
def test_breadth_first(data, result):
    """Test breadth first."""
    test_tree = bst.BinarySearchTree(data)
    test_array = []
    test_generator = test_tree.breadth_first()
    while len(test_array) < test_tree.size():
        test_array.append(next(test_generator))
    assert test_array == result
Пример #5
0
def test_in_order(data, result):
    """Test in_order."""
    test_tree = bst.BinarySearchTree(data)
    test_array = []
    test_generator = test_tree.in_order()
    while len(test_array) < test_tree.size():
        test_array.append(next(test_generator))
    assert test_array == result
Пример #6
0
def test_self_balancing():
    """Create 20 random trees of 50 numbers and check that they are self balancing."""
    import random
    for i in range(20):
        data = random.sample(range(1, 100), 50)
        test_tree = bst.BinarySearchTree(data)
        assert test_tree.balance() >= -1
        assert test_tree.balance() <= 1
Пример #7
0
 def test_insert_first(self):
     first_val = 9
     test_bst = bst.BinarySearchTree()
     test_bst.insert(first_val)
     expected = (9, None, None, None)
     actual = (test_bst.value, test_bst.left, test_bst.right,
               test_bst.parent)
     self.assertEquals(expected, actual)
Пример #8
0
def Bst_sort(a):
    B = bst.BinarySearchTree()
    i = 0
    while i < len(a):
        B.Insert(bst.CreateNode(a[i]))
        i += 1
    del a[:]
    Bst_inorder_to_list(B.root, a)
Пример #9
0
 def test_contain_big_tree(self):
     vals = [12, 2, 7, 14, 9]
     test_bst = bst.BinarySearchTree()
     for val in vals:
         test_bst.insert(val)
     actual_true = test_bst.contains(9)
     actual_false = test_bst.contains(1)
     self.assertEquals(actual_true, True)
     self.assertEquals(actual_false, False)
Пример #10
0
def test_deletion(data, delete_me, result):
    """Test if deletion works correctly."""
    test_tree = bst.BinarySearchTree(data)
    test_tree.deletion(delete_me)
    test_array = []
    test_generator = test_tree.in_order()
    while len(test_array) < test_tree.size():
        test_array.append(next(test_generator))
    assert test_array == result
Пример #11
0
 def test_unbalanced(self):
     #  12
     #  /
     # 9
     vals = [12, 9]
     test_bst = bst.BinarySearchTree()
     for val in vals:
         test_bst.insert(val)
     bal = test_bst.balance()
     self.assertEquals(bal, 1)
Пример #12
0
    def __init__(self, bucket_number, function='fnv'):
        """Init for our hash.

        Accepts a string to determine which hash the table uses.
        """
        self.bucket_list = []
        self.function = function
        self.bucket_number = bucket_number
        for i in range(bucket_number):
            self.bucket_list.append(bst.BinarySearchTree())
Пример #13
0
	def test_when_node_with_same_value_exists(self):
		e1 = b.Node(3)

		bst = b.BinarySearchTree(e1)

		bst.insert(3)

		self.assertEqual(bst.root.value, 3)
		self.assertEqual(bst.root.lchild, None)
		self.assertEqual(bst.root.rchild, None)
Пример #14
0
def test_insert(data, results):
    """Test if insertion works correctly."""
    test_tree = bst.BinarySearchTree()
    assert test_tree.root is None
    for i in data:
        test_tree.insert(i)
    assert test_tree.root.value == results[0]
    assert test_tree.root.right.value == results[1]
    assert test_tree.root.left.value == results[2]
    assert test_tree.root.left.right.value == results[3]
Пример #15
0
 def test_insert_two(self):
     first_val = 9
     second_val = 7
     test_bst = bst.BinarySearchTree()
     test_bst.insert(first_val)
     test_bst.insert(second_val)
     expected = (9, None, 7, None, None, 9)
     actual = (test_bst.value, test_bst.right,
               test_bst.left.value, test_bst.left.left,
               test_bst.left.right, test_bst.left.parent.value)
     self.assertEquals(expected, actual)
Пример #16
0
 def test_size(self):
     #    12             12
     #   /  \           /  \
     #  9    14        2    14
     #                / \   / \
     #               1   7 13  15
     #                  / \
     #                 6   9
     vals1 = [12, 9, 14]
     vals2 = [12, 2, 7, 14, 9, 6, 1, 13, 15]
     test_bst1 = bst.BinarySearchTree()
     test_bst2 = bst.BinarySearchTree()
     for val in vals1:
         test_bst1.insert(val)
     for val in vals2:
         test_bst2.insert(val)
     actual1 = test_bst1.size()
     actual2 = test_bst2.size()
     self.assertEquals(actual1, 3)
     self.assertEquals(actual2, 9)
Пример #17
0
    def test_it(self):
        """generates a number of arrays of increasing size each of random integers and tests them over
        the given functions. Eventually adds the results to the self.test_result dictionary with template:

        {function: {size_array: time_mean}, function_se: {size_array: time_confint}}

        """
        for key, arr in self.array_pool.items():
            # sorting algorithms

            self._test_it_quick_sort(key, arr)
            self._test_it_merge_sort(key, arr)
        print("sorting timing done!")

        # BSTs implementation

        insertion_counter = 0
        global tree
        tree = bst.BinarySearchTree()
        for bst_key in self.array_pool[DEFAULT_NUMBER]:
            insertion_counter += 1
            if insertion_counter in self.array_pool.keys():
                self._test_it_binary_get_max(insertion_counter)
                self._test_it_binary_get_random(insertion_counter)
                # testing over 30 randomnumber AND NOT CHANGING THE TREE
                self._test_it_binary_insertion_deletion(
                    insertion_counter,
                    random.sample(self.array_pool[DEFAULT_NUMBER], k=50))
                tree.put(bst_key, 0)
            else:
                # KEY, VALUE
                tree.put(bst_key, 0)
        print(
            "binary insertion, get random, get max and deletion timing done!")

        # heap implementation
        global heaper
        heaper = []
        heap_counter = 0
        for heap_key in self.array_pool[DEFAULT_NUMBER]:
            heap_counter += 1
            if heap_counter in self.array_pool.keys():
                # they will add values to heap_temp
                self._test_it_heap_get_max(heap_counter)
                # NOT CHANGING THE HEAP
                self._test_it_heap_insert_delete(
                    heap_counter,
                    random.sample(self.array_pool[DEFAULT_NUMBER], k=50))
                heapq.heappush(heaper, heap_key)
            else:
                heapq.heappush(heaper, heap_key)
        print("heap insertion, get max and deletion timing done!")

        self._pandator()
Пример #18
0
 def test_delete_rebalance_no_children(self):
     #          20
     #         /  \
     #        15   25
     #       /
     #      10
     vals = [20, 15, 25, 10]
     test_bst = bst.BinarySearchTree()
     for val in vals:
         test_bst.insert(val)
     test_bst.delete(25)
     self.assertEquals(15, test_bst.value)
Пример #19
0
 def test_depth(self):
     #    12             12
     #   /  \           /  \
     #  9    14        2    14
     #                / \   / \
     #               1   7 13  15
     #                  / \
     #                 6   9
     vals1 = [12, 9, 14]
     vals2 = [12, 2, 7, 14, 9, 6, 1, 13, 15]
     test_bst1 = bst.BinarySearchTree()
     test_bst2 = bst.BinarySearchTree()
     for val in vals1:
         test_bst1.insert(val)
     for val in vals2:
         test_bst2.insert(val)
     expected1 = 2
     expected2 = 4
     actual1 = test_bst1.depth()
     actual2 = test_bst2.depth()
     self.assertEquals(actual1, expected1)
     self.assertEquals(actual2, expected2)
Пример #20
0
 def test_balance_even(self):
     #    12
     #   /  \
     #  9    14
     vals1 = [12, 9, 14]
     test_bst1 = bst.BinarySearchTree()
     for val in vals1:
         test_bst1.insert(val)
     bal = test_bst1.balance()
     self.assertEquals(bal, 0)
     more_vals = [10, 2, 13, 17]
     for val in more_vals:
         test_bst1.insert(val)
     bal = test_bst1.balance()
     self.assertEquals(bal, 0)
Пример #21
0
def test_post_order_traversal(capsys):
    #          20
    #         /  \
    #        15   25
    #       /     /\
    #      10    24 26
    #                \
    #                 27
    vals = [20, 15, 25, 10, 26, 24, 27]
    test_bst = bst.BinarySearchTree()
    for val in vals:
        test_bst.insert(val)
    test_bst.post_order_traversal(test_bst)
    out, err = capsys.readouterr()
    expected = ['10', '15', '24', '25', '26', '27', '20']
    actual = out.split('\n')[:-1]
    assert actual == expected
Пример #22
0
 def test_insert_three1(self):
     #  9
     # / \
     #7   12
     first_val = 9
     second_val = 7
     third_val = 12
     test_bst = bst.BinarySearchTree()
     test_bst.insert(first_val)
     test_bst.insert(second_val)
     test_bst.insert(third_val)
     expected = (9, 7, None, None, 12, None, None, 9, 9)
     actual = (test_bst.value, test_bst.left.value, test_bst.left.left,
               test_bst.left.right, test_bst.right.value,
               test_bst.right.left, test_bst.right.right,
               test_bst.right.parent.value, test_bst.left.parent.value)
     self.assertEquals(expected, actual)
Пример #23
0
	def test_when_node_with_same_value_does_not_exist(self):
		e1 = b.Node(20)
		bst = b.BinarySearchTree(e1)

		bst.insert(30)
		bst.insert(40)
		bst.insert(25)
		bst.insert(31)
		bst.insert(38)
		bst.insert(43)

		self.assertEqual(bst.root.lchild, None)
		self.assertEqual(bst.root.rchild.value, 30)
		self.assertEqual(bst.root.rchild.lchild.value, 25)
		self.assertEqual(bst.root.rchild.rchild.value, 40)
		self.assertEqual(bst.root.rchild.rchild.lchild.value, 31)
		self.assertEqual(bst.root.rchild.rchild.lchild.rchild.value, 38)
Пример #24
0
def test_tree_always_retains_proper_nodes_when_one_is_deleted():
    """Create 10x99 random trees of varying numbers and check that no numbers are accidentally dropped upon deletion.

    Also used to hit edge cases we may not be able to come up with.
    This test faces errors when i iterates above 100. It is a nested
    for loop to ensure 100% coverage, though the code still has 98-100%
    with only the lower loop. Random chance determines which edge cases it hits.
    """
    import random
    for x in range(10):
        for i in range(99):
            data = random.sample(range(1, 100), i + 1)
            test_tree = bst.BinarySearchTree(data)
            num = random.randint(0, i)
            test_tree.deletion(data[num])
            del data[num]
            test_array = []
            test_generator = test_tree.in_order()
            while len(test_array) < test_tree.size():
                test_array.append(next(test_generator))
            assert test_array == sorted(data)
Пример #25
0
 def test_delete_rebalance_one_child(self):
     #          20
     #         /  \
     #        15   25
     #       /     /\
     #      10    24 26
     #                \
     #                 27
     vals = [20, 15, 25, 10, 26, 24, 27]
     test_bst = bst.BinarySearchTree()
     for val in vals:
         print val
         test_bst.insert(val)
     self.assertTrue(test_bst.contains(25))
     test_bst.delete(15)
     #         25
     #        /  \
     #       20  26
     #       / \    \
     #      10  24   27
     self.assertEquals(25, test_bst.value)
Пример #26
0
 def test_insert_many_self_balance(self):
     #     12
     #    / \
     #   10   13
     #   /\
     #  9 11
     # /
     # 8
     # SELF BALANCE =>
     #     10
     #    / \
     #   9   12
     #  /   / \
     # 8   11  13
     vals = (12, 13, 10, 11, 9, 8)
     test_bst = bst.BinarySearchTree()
     for val in vals:
         test_bst.insert(val)
     self.assertEquals(3, test_bst.depth())
     self.assertEquals(10, test_bst.value)
     self.assertEquals(8, test_bst.left.left.value)
Пример #27
0
 def test_insert_three2_self_balance(self):
     #     12
     #      \
     #       13
     #        \
     #         14
     # SELF BALANCE =>
     #   13
     #  / \
     # 12  14
     first_val = 12
     second_val = 13
     third_val = 14
     test_bst = bst.BinarySearchTree()
     test_bst.insert(first_val)
     test_bst.insert(second_val)
     test_bst.insert(third_val)
     print test_bst.value, test_bst.left.value, test_bst.left.left
     expected = (13, 12, None, None, 14, None, None, 13, 13)
     actual = (test_bst.value, test_bst.left.value, test_bst.left.left,
               test_bst.left.right, test_bst.right.value,
               test_bst.right.left, test_bst.right.right,
               test_bst.right.parent.value, test_bst.left.parent.value)
     self.assertEquals(actual, expected)
Пример #28
0
 def test_insert_three3_self_balance(self):
     #     12
     #     /
     #    11
     #    /
     #   10
     # SELF BALANCE =>
     #   11
     #  / \
     # 10  12
     first_val = 12
     second_val = 11
     third_val = 10
     test_bst = bst.BinarySearchTree()
     test_bst.insert(first_val)
     test_bst.insert(second_val)
     test_bst.insert(third_val)
     print test_bst.value, test_bst.left.value, test_bst.left.left
     expected = (11, 10, None, None, 12, None, None, 11, 11)
     actual = (test_bst.value, test_bst.left.value, test_bst.left.left,
               test_bst.left.right, test_bst.right.value,
               test_bst.right.left, test_bst.right.right,
               test_bst.right.parent.value, test_bst.left.parent.value)
     self.assertEquals(actual, expected)
Пример #29
0
    def setUp(self):

        self.worst_bst = bst.BinarySearchTree()
        for each_integer in range(0, 20):
            self.worst_bst.insert(each_integer)

        self.empty_bst = bst.BinarySearchTree()

        with self.assertRaises(TypeError):
            bst.BinarySearchTree("Not valid")

        with self.assertRaises(TypeError):
            bst.BinarySearchTree([55, 2, 1])

        with self.assertRaises(TypeError):
            bst.BinarySearchTree(42)

        with self.assertRaises(TypeError):
            bst.BinarySearchTree(None)
Пример #30
0
    valid = l_valid and r_valid
    if valid:
        if l_max is not None:
            valid = valid and l_max < node.key
        if r_max is not None:
            valid = valid and r_max >= node.key
    return valid, min(r_min, node.key), max(r_max, node.key)


def validate(tree):
    return _validate(tree.root)[0]


if __name__ == '__main__':
    tree = bst.BinarySearchTree()
    tree.add('X', 1)
    tree.add('B', 2)
    tree.add('Q', 3)
    tree.add('A', 2)
    print validate(tree)

    # Concoct an invalid tree.
    tree = bst.BinarySearchTree()
    tree.root = bst.Node('G', 2)
    tree.root.left = bst.Node('B', 3)
    tree.root.left.right = bst.Node('C', 4)
    tree.root.left.left = bst.Node('X', 5)

    print validate(tree)