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 testIt(): #This stree is unbalanced: newBST = BST() newBST.insert("testitroot", -2) newBST.insert("testitl", 0) newBST.insert("testitr", -1) newBST.insert("testitrl", 0) newBST.insert("testitrr", -1) newBST.insert("testitrrr", 0) print("the current tree is balanced: " + str(isBalanced(newBST))) #SHOULD RETURN FALSE #This tree should be balanced: newBST2 = BST() newBST.insert("testitroot", 7) newBST.insert("testitl", 3) newBST.insert("testitr", 11) newBST.insert("testitlr", 5) newBST.insert("testitll", 1) newBST.insert("testitrl", 9) newBST.insert("testitrr", 13) print("the current tree is balanced: " + str(isBalanced(newBST2))) #Should return True 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
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_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 test_closest_to_two_and_three_quarters_without_three(self): spy_float_distance = mock.MagicMock() spy_float_distance.side_effect = self.float_distance tree = BST(2., BST(1.)) closest_to, distance = tree.closest_to(2.75, spy_float_distance) self.assertEqual(closest_to, 2) self.assertEqual(distance, 0.75) calls_args = spy_float_distance.call_args_list expected_calls_args = [mock.call(2.75, 2)] self.assertEqual(calls_args, expected_calls_args)
def test_closest_to_four_with_degenerate_tree(self): spy_float_distance = mock.MagicMock() spy_float_distance.side_effect = self.float_distance tree = BST(1, None, BST(2, None, BST(3))) closest_to, distance = tree.closest_to(4, spy_float_distance) self.assertEqual(closest_to, 3) self.assertEqual(distance, 1) calls_args = spy_float_distance.call_args_list expected_calls_args = [mock.call(4, 3)] self.assertEqual(calls_args, expected_calls_args)
def test_init(): """implement a heap that can be either min or max the choice is possible at initialization time. It defaults to an empty heap but allows initialization with an iterable""" assert isinstance(BST(), BST) with pytest.raises(TypeError): BST([1, 2, 3, 4]) # May implement this later with pytest.raises(TypeError): BST(1, 2, 3, 4) # Also could be implemented (limited use though)
def test_empty_tree(self): bst = BST() assert bst.root is None assert bst.is_empty() is True assert bst.size == 0 assert bst.levels == 0 assert bst.__repr__() == "BST(serialize='')" assert bst.serialize() == '' assert bst.level_order() == [] assert bst.pre_order() == [] assert bst.in_order() == [] assert bst.post_order() == [] assert bst == BST()
def axis_aligned_hypotheses(dataset): """ Given a dataset in R2, return an iterator over hypotheses that result in distinct classifications of those points. Classifiers are axis-aligned rectangles Args: dataset: The dataset to use to generate hypotheses """ validRectangles = [[(float('inf'), float('inf')), (float('inf'), float('inf'))]] xTree = BST() yTree = BST() ydataset = [(point[1], point[0]) for point in dataset] [xTree.insert(point) for point in dataset] [yTree.insert(point) for point in ydataset] for i in range(1, len(dataset) + 1): d = combinations(dataset, i) l = [] for comb in d: min_x = min(comb, key=operator.itemgetter(0))[0] max_x = max(comb, key=operator.itemgetter(0))[0] min_y = min(comb, key=operator.itemgetter(1))[1] max_y = max(comb, key=operator.itemgetter(1))[1] xRange = [] yRange = [] # Generate list of points in each range (x,y) for r in xTree.range(min_x, max_x): xRange.append(r.key) for r in yTree.range(min_y, max_y): point = r.key yRange.append((point[1], point[0])) # Check for points in both ranges bothHave = [] for point in xRange: if point in yRange and point not in bothHave: bothHave.append(point) # Valid only if length of combination == length of points both have if len(comb) == len(bothHave): validRectangles.append([(min_x - 0.1, min_y - 0.1), (max_x + 0.1, max_y + 0.1)]) drawRectangles.append(validRectangles[-1]) for vr in validRectangles: yield AxisAlignedRectangle(vr[0][0], vr[0][1], vr[1][0], vr[1][1])
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
def test_interface(self): """ Tests that the publically exposed methods are available """ bst = BST() # test 'insert' attribute exists ad is a callable self.assertTrue(hasattr(bst, 'insert')) self.assertTrue(callable(getattr(bst, 'insert'))) # test 'find' attribute exists and is a callable self.assertTrue(hasattr(bst, 'find')) self.assertTrue(callable(getattr(bst, 'find'))) # test 'breadth_first_search' attribute exists and is a callable self.assertTrue(hasattr(bst, 'breadth_first_search')) self.assertTrue(callable(getattr(bst, 'breadth_first_search'))) # test 'depth_first_pre_order_search' attribute exists and is a callable self.assertTrue(hasattr(bst, 'depth_first_pre_order_search')) self.assertTrue(callable(getattr(bst, 'depth_first_pre_order_search'))) # test 'depth_first_post_order_search' attribute exists and is a callable self.assertTrue(hasattr(bst, 'depth_first_post_order_search')) self.assertTrue( callable(getattr(bst, 'depth_first_post_order_search'))) # test 'depth_first_in_order_search' attribute exists and is a callable self.assertTrue(hasattr(bst, 'depth_first_in_order_search')) self.assertTrue( callable(getattr(bst, 'depth_first_in_order_search')))
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
def main(): tree = BST() lst = [50, 25, 75, 12, 35, 55, 80] for _ in lst: tree.insert(_, "hello") postorder(tree.root)
def test_delete_node(self): bst = BST() bst.insert_node(50, "node50") bst.insert_node(30, "node30") bst.insert_node(20, "node20") bst.insert_node(40, "node40") bst.insert_node(70, "node70") bst.insert_node(60, "node60") bst.insert_node(80, "node80") smallest = bst.smallest() self.assertTrue(smallest == 20) logging.debug("BST root: %s" % str(bst.to_list())) bst.delete_node(30) logging.debug("BST root: %s" % str(bst.to_list())) self.assertTrue(bst.root.left.value == 40) self.assertTrue(bst.root.left.left.value == 20) logging.debug("BST root: %s" % str(bst.to_list())) bst.delete_node(100) bst.delete_node(70) logging.debug("BST root: %s" % str(bst.to_list())) self.assertTrue(bst.root.right.value == 80) self.assertTrue(bst.root.right.left.value == 60) bst.delete_node(50) logging.debug("BST root: %s" % str(bst.to_list())) self.assertTrue(bst.root.value == 60) self.assertTrue(bst.root.left.value == 40) self.assertTrue(bst.root.right.value == 80)
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 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
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 test_bst_delete(my_tree): bst = BST(my_tree) vals = [val for val in my_tree.values if val != None] for val in vals[:-1]: bst.delete(val) assert bst.root.is_bst == True
def test_insert_1(self): print("Running test_insert_1") h = BST([5, 2, 8, 1, 3, 9]) self.check_multiline( str(h), [["5"], ["2", "8"], ["1", "3", "_", "9"], ["_", "_", "_", "_", "_", "_"], ["1", "2", "3", "5", "8", "9"]])
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 basic_setup(): """A basic setup with two numbers.""" from bst import BST b = BST() b.insert(9) b.insert(10) return b
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
def test_building_to_fancier03(): """Building. First major obstacle.""" from bst_balancing import BST b = BST() b.insert(100) b.insert(200) b.insert(175) b.insert(190) b.insert(180) assert b.root.value == 175 assert b.root.left_depth == 1 assert b.root.right_depth == 2 assert b.root.left.value == 100 assert b.root.left.left_depth == 0 assert b.root.left.right_depth == 0 assert b.root.left.parent.value == 175 assert b.root.right.value == 190 assert b.root.right.left_depth == 1 assert b.root.right.right_depth == 1 assert b.root.right.left.value == 180 assert b.root.right.left.right_depth == 0 assert b.root.right.left.left_depth == 0 assert b.root.right.right.value == 200 assert b.root.right.right.right_depth == 0 assert b.root.right.right.left_depth == 0
def test_init_bst(self): """ Test initialization of BST """ bst = BST() self.assertIsInstance(bst, BST) self.assertIsNone(bst.root)
def test_bst_get_range(my_tree): print(my_tree) bst = BST(my_tree) low = 1 high = 6 res = bst.get_range(low, high) assert res == [3, 5, 6] low = 0 high = 20 res = bst.get_range(low, high) assert res == [3, 5, 6, 8, 10, 11, 13] low = 20 high = 0 res = bst.get_range(low, high) assert res == [] low = 6.5 high = 7 res = bst.get_range(low, high) assert res == [] low = 8 high = 8 res = bst.get_range(low, high) assert res == [8]
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
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"]])
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_long_tree(self): print("Running test_long_tree") h = BST([20, 10, 25, 5, 18, 13, 15]) self.check_multiline(str(h), [["20"], ["10", "25"], ["5", "18", "_", "_"], ["_", "_", "13", "_"], ['_', '15'], ['_', '_'], ["5", "10", "13", "15", "18", "20", "25"]])