def solve_with_bst(self): nb_solutions = 0 small_x, small_y = 0, 0 active_segments = defaultdict(list) r = bst.Node(0) for y in xrange(self.col+1): new_segment = g.dh_lines[y] end_segment = active_segments[y] == y vertical_range = g.dv_lines[y] if new_segment: #there is a new left endpoint # TODO consider new_segment as a possible list left_endpoint = new_segment[0][0] right_endpoint = new_segment[0][1] node_value = new_segment[1] bst.insert(r, bst.Node(node_value)) active_segments[right_endpoint].append(node_value) if end_segment: # if the segment coming to an end active_segments[y].remove(end_segment) bst.delete(r,end_segment) if vertical_range: solutions = bst.search_range(r, vertical_range[0],vertical_range[1]) if solutions: if not small_x: small_x, small_y = [solutions[0],y] nb_solutions += len(solutions) print nb_solutions, small_x, small_y
def test_create_Node(self): test_node = bst.Node(5) test_node1 = bst.Node(500) self.assertEqual("<class 'bst.Node'>", str(type(test_node1))) self.assertEqual("<class 'bst.Node'>", str(type(test_node))) self.assertEqual(test_node.data, 5) self.assertEqual(test_node1.data, 500)
def _insert(self, key, node): if key < node.key: if node.left: self._insert(key, node.left) else: node.left = bst.Node(key, parent=node) self.splay(node.left) else: if node.right: self._insert(key, node.right) else: node.right = bst.Node(key, parent=node) self.splay(node.right)
def test_in(self): head = bst.Node(10) head.add(11) head.add(9) self.assertTrue(10 in head) self.assertFalse(13 in head)
def test_add(self): head = bst.Node(10) head.add(11) head.add(9) self.assertEqual(head.value, 10) self.assertEqual(head._left.value, 9) self.assertEqual(head._right.value, 11)
def test_add_Node_to_Node(self): test_head = bst.Node(5) bst.add_node_to_tree(test_head, 4) bst.add_node_to_tree(test_head, 6) self.assertEqual(test_head.data, 5) self.assertEqual(test_head.left.data, 4) self.assertEqual(test_head.right.data, 6)
def test_is_balanced(self): head = bst.Node(10) head.add(11) head.add(9) head.add(13) head.add(14) head.add(18) self.assertFalse(head.is_balanced)
def test_height(self): head = bst.Node(10) head.add(11) head.add(9) head.add(13) head.add(14) head.add(18) self.assertEqual(head.get_height(), 5)
def testRandomInsert(): root = bst.Node(random.randint(0, 1000)) start = time.time() for i in range(100000): bst.insert(root, random.randint(0, 1000), 0) end = time.time() print('Time Elapsed: {0}\tAverage Time per insert: {1}'.format( end - start, (end - start) / 100000))
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)
def testInOrderInsert(): root = bst.Node(500) for i in range(1000): bst.insert(root, i, 0) if bst.find(root, 100) is None: print("Shouldn't be None") else: print('Found 100') bst.inorder(root)
def test_traverse_postorder(self): head = bst.Node(10) head.add(11) head.add(9) head.add(13) head.add(14) head.add(18) out = [] head.traverse_postorder(out.append) self.assertEqual(out, [9, 18, 14, 13, 11, 10])
def test_rebalanced(self): head = bst.Node(10) head.add(11) head.add(9) head.add(13) head.add(14) head.add(18) self.assertFalse(head.is_balanced) print(head.get_height()) head = head.rebalance() self.assertTrue(head.is_balanced) print(head.get_height())
def bst_experiment(n, type='t'): root = bst.Node() experiment_data = "{};".format(n) clk_start = time.time() results = get_results(n) for el in results: bst.insert(root, el) experiment_data += str(time.time()-clk_start) experiment_data += ';' clk_start = time.time() bst.insert(root, "adelaida") experiment_data += str(time.time()-clk_start) experiment_data += ';' index = randint(0, len(results) - 1) clk_start = time.time() _, root = bst.delete(root, results[index]) experiment_data += str(time.time()-clk_start) experiment_data += ';' index = randint(0, len(results) - 1) clk_start = time.time() bst.find(root, results[index]) experiment_data += str(time.time()-clk_start) experiment_data += ';' clk_start = time.time() bst.tree_max(root) experiment_data += str(time.time()-clk_start) experiment_data += ';' clk_start = time.time() bst.tree_min(root) experiment_data += str(time.time()-clk_start) experiment_data += ';' index = randint(0, len(results) - 1) clk_start = time.time() bst.successor(root, results[index]) experiment_data += str(time.time()-clk_start) experiment_data += ';' clk_start = time.time() bst.inorder_stat(root) experiment_data += str(time.time()-clk_start) experiment_data += '\n' return experiment_data
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)
def test3(): root = bst.Node(15, left=bst.Node(10, right=bst.Node(14, right=bst.Node(16)))) # bst.verify_is_bst(root) assert not bst.verify_is_bst(root)
def test2(): root = bst.Node(15, left=bst.Node(16, left=bst.Node(16))) # bst.verify_is_bst(root) assert not bst.verify_is_bst(root)
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)
https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/ """ import bst def is_mirror(root1, root2): if root1 is None and root2 is None: return True if root1 is None or root2 is None: return False if root1.value != root2.value: return False return is_mirror(root1.left, root2.right) and is_mirror(root1.right, root2.left) # tests print(is_mirror(bst.from_ordered_list([]), bst.from_ordered_list([]))) print(is_mirror(bst.from_ordered_list([1]), bst.from_ordered_list([1]))) print(is_mirror(bst.from_ordered_list([1,3,6,9,11]), bst.from_ordered_list([1,3,6,9,11]))) root2 = bst.Node(3) bst.add_node(root2, 11) bst.add_node(root2, 1) bst.add_node(root2, 9) bst.add_node(root2, 6) print(is_mirror(bst.from_ordered_list([1,3,6,9,11]), root2))
def testHeight(): root = bst.Node(500) for i in range(1000): bst.insert(root, i, 0) print(bst.find(root, 199).height)
return temp.data # print bst in order def printBbst(root): if root: printBbst(root.left) print(root.data, end=' ') printBbst(root.right) # Part 5a print('Part 5.a. --- Random Array') randomArray = arr_ints.getRandomArray(10000) bst.root = bst.insertRec(None, bst.Node(randomArray[0])) for n in randomArray[1:]: bst.insertRec(bst.root, bst.Node(n)) print('created bst from 10000 elements -- Recursive') root = insertIter(None, Node(randomArray[0])) for n in randomArray[1:]: insertIter(root, Node(n)) print('created avl tree from 10000 elements -- Iterative') # Part 5c print('\n\nPart 5.c. --- Random Array') randomArray = arr_ints.getRandomArray(10000)
if len(v1Stack) < len(v2Stack): shorter = v1Stack longer = v2Stack else: shorter = v2Stack longer = v1Stack minShorterIndex = -1 for val in range(len(shorter)): if shorter[val] in longer: minShorterIndex = val return shorter[minShorterIndex].value if __name__ == '__main__': # root = bst.Node(4) # root.left = bst.Node(2) # root.left.left = bst.Node(1) # root.left.right = bst.Node(3) # root.right = bst.Node(7) # root.right.left = bst.Node(6) # print(lca(root, 1,7)) root = bst.Node(2) root.left = bst.Node(1) root.right = bst.Node(3) root.right.right = bst.Node(5) root.right.right.left = bst.Node(4) root.right.right.right = bst.Node(6) print(lca_rec(root, 4, 6))
def stat(): with open('data/experiment.txt', 'r') as f: arg = f.read() arg = arg.split('\n') with open('data/with_dupl.txt', 'r') as f: arg_rep = f.read() arg_rep = arg_rep.split('\n') # "\n" arg.pop(-1) arg_rep.pop(-1) arg = arg[:900] arg_rep = arg_rep[:900] for n in range(100, 901, 100): words = arg.copy() words_rep = arg_rep.copy() for i in range(900 - n): words.pop(randint(0, (len(words) - 1))) words_rep.pop(randint(0, len(words_rep) - 1)) root = bst.Node() rbt_root = rbt.RBT() hmap_root = hmap.HMAP_tree(n // 4) for i in range(len(words)): bst.insert(root, words[i]) rbt_root.insert(words[i]) hmap_root.insert(words[i]) min_val = bst.tree_min(root).value max_val = bst.tree_max(root).value random_val = words[randint(0, len(words))] t.compares = 0 bst.find(root, min_val) min_c = t.compares t.compares = 0 bst.find(root, max_val) max_c = t.compares t.compares = 0 bst.find(root, random_val) random_c = t.compares # n, minimum, maximum, random with open('data/bst_limits.txt', 'a') as f: f.write('{};{};{};{}\n'.format(n, min_c, max_c, random_c)) t.compares = 0 rbt_root.find(min_val) min_c = t.compares t.compares = 0 rbt_root.find(max_val) max_c = t.compares t.compares = 0 rbt_root.find(random_val) random_c = t.compares with open('data/rbt_limits.txt', 'a') as f: f.write('{};{};{};{}\n'.format(n, min_c, max_c, random_c)) t.compares = 0 hmap_root.find(min_val) min_c = t.compares t.compares = 0 hmap_root.find(max_val) max_c = t.compares t.compares = 0 hmap_root.find(random_val) random_c = t.compares with open('data/hmap_limits.txt', 'a') as f: f.write('{};{};{};{}\n'.format(n, min_c, max_c, random_c)) root = bst.Node() rbt_root = rbt.RBT() hmap_root = hmap.HMAP_tree(n // 4) for i in range(len(words_rep)): bst.insert(root, words_rep[i]) rbt_root.insert(words_rep[i]) hmap_root.insert(words_rep[i]) min_val = bst.tree_min(root).value max_val = bst.tree_max(root).value random_val = words[randint(0, len(words))] t.compares = 0 bst.find(root, min_val) min_c = t.compares t.compares = 0 bst.find(root, max_val) max_c = t.compares t.compares = 0 bst.find(root, random_val) random_c = t.compares with open('data/bst_limits.txt', 'a') as f: f.write('{};{};{};{}\n'.format(n, min_c, max_c, random_c)) t.compares = 0 rbt_root.find(min_val) min_c = t.compares t.compares = 0 rbt_root.find(max_val) max_c = t.compares t.compares = 0 rbt_root.find(random_val) random_c = t.compares with open('data/rbt_limits.txt', 'a') as f: f.write('{};{};{};{}\n'.format(n, min_c, max_c, random_c)) t.compares = 0 hmap_root.find(min_val) min_c = t.compares t.compares = 0 hmap_root.find(max_val) max_c = t.compares t.compares = 0 hmap_root.find(random_val) random_c = t.compares with open('data/hmap_limits.txt', 'a') as f: f.write('{};{};{};{}\n'.format(n, min_c, max_c, random_c))
import bst r = bst.Node(3) node = bst.BinarySearchTree() nodeList = [1, 8, 5, 12, 14, 6, 15, 7, 16, 8] for nd in nodeList: node.insert(r, bst.Node(nd)) print("------In order ---------") print(node.in_order_place(r)) print("------Pre order ---------") print(node.pre_order_place(r)) print("------Post order ---------") print(node.post_order_place(r)) print(bst.is_BST(r))
def main(): option = sys.argv if len(option) > 2: if option[1] == '--type': commands_count, commands = get_input() try: commands_count = int(commands_count) except ValueError: sys.stderr.write("Number of operations must be an integer!\n") return type = option[2] t.init_stats() clk_start = time.time() if type == 'bst': root = bst.Node() for command in commands: try: if len(command) != 0: if command[0] == 'insert': element = t.make_cut(command[1]) if element != -1: bst.insert(root, element) else: sys.stderr.write("Invalid symbol in {} \n".format(element)) continue elif command[0] == 'load': loaded = bst.load("data/{}".format(command[1])) if loaded != 0: root = loaded elif command[0] == 'delete': result, new_root = bst.delete(root, command[1]) while result == 1: result, new_root = bst.delete(root, command[1]) root = new_root elif command[0] == 'find': result, _ = bst.find(root, command[1]) print(result) elif command[0] == 'min': node = bst.tree_min(root) if node.value != None: print(node.value) else: print() elif command[0] == 'max': node = bst.tree_max(root) if node.value != None: print(node.value) else: print() elif command[0] == 'successor': result = bst.successor(root, command[1]) if result != 0: print(result) else: print() elif command[0] == 'inorder': bst.inorder(root) print() else: sys.stderr.write("Invalid command in ", command, ("\n")) continue except IndexError: sys.stderr.write("Invalid command parameters in ", command, ("\n")) continue elif type == 'rbt': tree = rbt.RBT() for command in commands: if len(command) != 0: if command[0] == 'insert': element = t.make_cut(command[1]) if element != -1: tree.insert(command[1]) else: sys.stderr.write("Invalid symbol in {} \n".format(element)) continue elif command[0] == 'load': tree = rbt.RBT() tree = tree.load("data/{}".format(command[1])) elif command[0] == 'delete': result = tree.delete(command[1]) while result == 1: result = tree.delete(command[1]) elif command[0] == 'find': result, _ = tree.find(command[1]) print(result) elif command[0] == 'min': minimum = tree.tree_min(tree.root) if minimum != None: print(minimum.value) else: print() elif command[0] == 'max': maximum = tree.tree_max(tree.root) if maximum != None: print(maximum.value) else: print() elif command[0] == 'successor': result = tree.successor(command[1]).value if result != None: print(result) else: print() elif command[0] == 'inorder': tree.inorder(tree.root) print() else: sys.stderr.write("Invalid symbol in {} \n".format(command)) continue elif type == 'hmap': tree = hmap.HMAP_tree(100) for command in commands: if len(command) != 0: if command[0] == 'insert': element = t.make_cut(command[1]) if element != -1: tree.insert(command[1]) else: sys.stderr.write("Invalid symbol in {} \n".format(element)) continue elif command[0] == 'load': result = tree.load("data/{}".format(command[1])) elif command[0] == 'delete': result = tree.delete(command[1]) while result == 1: result = tree.delete(command[1]) elif command[0] == 'find': print(tree.find(command[1])) elif command[0] == 'min': print() elif command[0] == 'max': print() elif command[0] == 'successor': print() elif command[0] == 'inorder': print() else: sys.stderr.write("Invalid symbol in {} \n".format(command)) continue else: sys.stderr.write("Invalid structure! Available: bst, rbt or hmap!\n") sys.stderr.write("\n") sys.stderr.write("Total time of excecution {}\n".format(time.time()-clk_start)) print_results() else: sys.stderr.write("Invalid argument! Use --type !\n") else: sys.stderr.write("Not enough arguments! \n")
def create_tree(node_list): tree = bst.Node(node_list[0]) for node in node_list[1:]: bst.add_node_to_tree(tree, node) return tree
def test1(): root = bst.Node(15) # bst.verify_is_bst(root) assert bst.verify_is_bst(root)
import bst import random if __name__ == "__main__": T = bst.Tree() for i in range(10): T.treeInsert(bst.Node(d = bst.Data(random.randint(0, 100)))) T.treeInsert(bst.Node(d = bst.Data(10))) print("Root: ", T.root.key()) T.inorderTreeWalk(T.root) print("---------------") n = T.treeSearch(T.root, 10) if n != None: T.treeDelete(T.treeMinimum(n)) print("---------------") T.inorderTreeWalk(T.root) print("Root: ", T.root.key()) print("Min ", T.treeMinimum(T.root).key()) print("Max: ", T.treeMaximum(T.root).key()) print("root successor: ", T.treeSuccessor(T.root).key())