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 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 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 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_bst_insert(self): t = None t = bst.insert(t, 4, 'four') t = bst.insert(t, 2, 'two') t = bst.insert(t, 5, 'five') t = bst.insert(t, 1, 'one') t = bst.insert(t, 0, 'zero') t = bst.insert(t, 3, 'three') t = bst.insert(t, 9, 'nine') t = bst.insert(t, 6, 'six') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 8, 'eight') self.assertEqual(t.key, 4)
def find_intersection(segments): #seperate start pts and end pts segPts = [] for pt in segments: segPts.append([pt[0],pt, 0]) #start pt segPts.append([pt[1],pt, 1]) #end pt #sort the segments by x value segPts.sort() #O(n log n) segTree = None for seg in segPts: #sweeping from left to right if seg[2] == 0: #it's a start pt if seg[1][0][1] == seg[1][1][1]: #horiz line segTree = insert(segTree, seg[1][0][1]) #insert the y value continue if seg[1][0][0] == seg[1][1][0]: #vertical line #check segTree for at least y start value of vert line bound = seg[1][0][1] #vert line y start val check = get_smallest_at_least(segTree, bound) if not check is None: if check.key < seg[1][1][1]: #the horiz y val is less than the vert line end pt y val xReturn = seg[1][0][0] yReturn = check.key return(xReturn, yReturn) if seg[2] == 1: #it's an end pt if seg[1][0][1] == seg[1][1][1]: #horiz line segTree = delete(segTree, seg[1][0][1]) else: continue #no intersections return None
def insert(root, x): assert root.is_valid node = bst.insert(root, x) node.is_black = False fix_rbtree(node) assert root.is_valid
def insert(root, x): #not finished assert root.is_valid node = bst.insert(root) node.is_black = False fix_rbtree(node) assert root.is_valid
def put(self, key, val): """put a key value pair into the map, calls insert function in bst.py Args: key (*) : a key which is compareable by <,>,== val (*): the value associated with the key """ self.tree = bst.insert(self.tree, key, val) self.num_items += 1
def find_intersection(segments): points=[] for i in range(len(segments)): if segments[i][0][0] == segments[i][1][0]: points.append((segments[i][0], 'v', segments[i])) #i ID'li VERTICAL line'a ait nokta elif segments[i][0][1] == segments[i][1][1]: points.append((segments[i][0], 'h')) #i ID'li HORIZONTAL line'a ait nokta points.append((segments[i][1], 'h')) points = sorted(points, key=lambda x: x[0][0]) #points.sort() #sorting points with respect to the x-coordinate values # set root to be an empty tree root = None if len(points) == 1: return None for i in range(len(points)): #print points #if point belongs to horizontal segments if points[i][1] == 'h': if search(root,points[i][0][1]) == None: #if not there then add it root = insert(root, points[i][0][1]) else: #if there then delete it root = delete(root, points[i][0][1]) #if vertical line else: #seg is the vertical line this point belongs to seg = points[i][2] y1 = seg[0][1] y2 = seg[1][1] ymin = min(y1,y2) ymax = max(y1,y2) least = get_smallest_at_least(root, ymin) if least == None: continue elif least.key <= ymax: return (seg[0][0], least.key) return None # asegment = [((1,4),(1,7)), ((1,5),(3,5))] # print find_intersection(asegment)
def put(self, key, val): """put a key value pair into the map Calls insert function in bst.py Args: key (str) : the key (last name) val (Classmate) : an object of Classmate """ self.tree = insert(self.tree, key, val)
def test_bst_contains(self): t = None # Empty tree self.assertFalse(bst.contains(t, 5)) t = bst.insert(t, 4, 'four') t = bst.insert(t, 2, 'two') t = bst.insert(t, 5, 'five') t = bst.insert(t, 1, 'one') t = bst.insert(t, 0, 'zero') t = bst.insert(t, 3, 'three') t = bst.insert(t, 9, 'nine') t = bst.insert(t, 6, 'six') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 8, 'eight') # Not Contained self.assertFalse(bst.contains(t, 44)) # Contained self.assertTrue(bst.contains(t, 2)) self.assertTrue(bst.contains(t, 8))
def test_bst_preorder_list(self): t = None # Empty tree self.assertEqual(bst.preorder_list(t), None) # 1 Node t = bst.insert(t, 4, 'four') self.assertEqual(bst.preorder_list(t), [4]) t = bst.insert(t, 2, 'two') # self.assertEqual(bst.find_max(t), (2, 'two')) t = bst.insert(t, 5, 'five') t = bst.insert(t, 1, 'one') t = bst.insert(t, 0, 'zero') t = bst.insert(t, 3, 'three') t = bst.insert(t, 9, 'nine') t = bst.insert(t, 6, 'six') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 8, 'eight') # List inorder from populated list self.assertEqual(bst.preorder_list(t), [4, 2, 1, 0, 3, 5, 9, 6, 7, 8])
def put(self, key, val): """put a key value pair into the map Calls insert function in bst.py Args: key (any) : a key which is compareable by <,>,== val (any): the value associated with the key """ #this method is already written for you self.tree = bst.insert(self.tree, key, val) self.num_items += 1
def test_bst_find_max(self): t = None # Empty tree self.assertEqual(bst.find_max(t), (None, None)) t = bst.insert(t, 2, 'two') # 1 Node self.assertEqual(bst.find_max(t), (2, 'two')) t = bst.insert(t, 5, 'five') t = bst.insert(t, 1, 'one') t = bst.insert(t, 0, 'zero') t = bst.insert(t, 3, 'three') t = bst.insert(t, 9, 'nine') t = bst.insert(t, 6, 'six') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 8, 'eight') # Finding max in populated list self.assertEqual(bst.find_max(t), (9, 'nine'))
def test_bst1(self): t = None t = bst.insert(t, 4, 'four') t = bst.insert(t, 2, 'two') t = bst.insert(t, 3, 'three') t = bst.insert(t, 1, 'one') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 5, 'five') t = bst.insert(t, 6, 'six') self.assertEqual(t.key, 4)
def tree( draw, key_gen: some.SearchStrategy[Ex] = some.integers() ) -> Tuple[Optional[Tree[Ex]], Sequence[Ex]]: """Strategy to produce a tree and the list of values used to create the tree.""" keys = draw(some.lists(key_gen)) # type: Sequence[Ex] tree = None for value in keys: tree = insert(tree, Node(key=value)) return (tree, keys)
def test_bst2(self): t = None t = bst.insert(t, 4, 'four') t = bst.insert(t, 2, 'two') t = bst.insert(t, 3, 'three') t = bst.insert(t, 1, 'one') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 5, 'five') t = bst.insert(t, 6, 'six') self.assertEqual(bst.tree_height(t), 3)
def test_bst_tree_height(self): t = None # Empty tree self.assertEqual(bst.tree_height(t), None) # 1 Node t = bst.insert(t, 4, 'four') self.assertEqual(bst.tree_height(t), 0) t = bst.insert(t, 2, 'two') self.assertEqual(bst.tree_height(t), 1) # self.assertEqual(bst.find_max(t), (2, 'two')) t = bst.insert(t, 5, 'five') t = bst.insert(t, 1, 'one') self.assertEqual(bst.tree_height(t), 2) t = bst.insert(t, 0, 'zero') self.assertEqual(bst.tree_height(t), 3) t = bst.insert(t, 3, 'three') t = bst.insert(t, 9, 'nine') t = bst.insert(t, 6, 'six') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 8, 'eight') self.assertEqual(bst.tree_height(t), 5)
def put(self, key, val): """put a key value pair into the map Calls insert function in bst.py and increments num_items by 1 Args: key (any) : a key which is compareable by <,>,== val (any): the value associated with the key """ self.tree = bst.insert(self.tree, key, val) # Check if an item was actually inserted, or just replaced if len(bst.inorder_list(self.tree, [])) > self.num_items: self.num_items += 1
def test_bst_range_search(self): t = None min = 1 max = 7 # Empty tree self.assertEqual(bst.range_search(t, min, max), None) # 1 Node t = bst.insert(t, 4, 'four') self.assertEqual(bst.range_search(t, min, max), ['four']) t = bst.insert(t, 2, 'two') self.assertEqual(bst.range_search(t, min, max), ['two', 'four']) # self.assertEqual(bst.find_max(t), (2, 'two')) t = bst.insert(t, 5, 'five') t = bst.insert(t, 1, 'one') t = bst.insert(t, 0, 'zero') self.assertEqual(bst.range_search(t, min, max),\ ['one', 'two', 'four', 'five']) t = bst.insert(t, 3, 'three') t = bst.insert(t, 9, 'nine') t = bst.insert(t, 6, 'six') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 8, 'eight') self.assertEqual(bst.range_search(t, min, max),\ ['one', 'two', 'three', 'four', 'five', 'six'])
def test_bst4(self): t = None t = bst.insert(t, 4, 'four') t = bst.insert(t, 2, 'two') t = bst.insert(t, 3, 'three') t = bst.insert(t, 1, 'one') t = bst.insert(t, 7, 'seven') t = bst.insert(t, 5, 'five') t = bst.insert(t, 6, 'six') t = bst.delete(t, 6) self.assertEqual(bst.tree_height(t), 2) t = bst.delete(t, 7) self.assertEqual(bst.tree_height(t), 2) t = bst.delete(t, 4) self.assertEqual(bst.tree_height(t), 2) self.assertEqual(t.key, 5)
def find_intersection(segments): root = None line_dict = {el[0][0]: el for el in segments} for el in segments: root = insert(root, el[0][0]) test_node = get_smallest(root) test_key = test_node.key active_lines = [] while(True): test_line = line_dict[test_key] #discard old lines active_lines_copy = active_lines[:] for line in active_lines_copy: if test_key > line[1][0]: active_lines.remove(line) #either test line is a vertical line or a horizontal line if test_line[0][1] == test_line[1][1]: #horizontal line active_lines.append(test_line) else: #vertical line for line in active_lines: if line[0][1] > test_line[0][1] and line[0][1] < test_line[1][1]: return (test_line[0][0], line[0][1]) root = delete(root, test_key) test_node = get_smallest_at_least(root, test_key) if test_node == None: return None else: test_key = test_node.key
def test_bst_delete(self): t = None dummy_node = None #used to compare against bst 't' dummy_node = bst.insert(dummy_node, 2, 'two') # Empty tree self.assertRaises(KeyError, bst.delete, t, 5) # Deleting root t = bst.insert(t, 4, 'four') t = bst.delete(t, 4) # saves the delete self.assertEqual(t, None) # Deleting root single child t = bst.insert(t, 2, 'two') t = bst.insert(t, 5, 'five') self.assertEqual(bst.delete(t, 5), dummy_node) # Checking KeyError for non-empty tree self.assertRaises(KeyError, bst.delete, t, 99) t2 = None t2 = bst.insert(t2, 4, 'four') t2 = bst.insert(t2, 2, 'two') t2 = bst.insert(t2, 5, 'five') t2 = bst.insert(t2, 1, 'one') t2 = bst.insert(t2, 0, 'zero') t2 = bst.insert(t2, 3, 'three') t2 = bst.insert(t2, 9, 'nine') t2 = bst.insert(t2, 6, 'six') t2 = bst.insert(t2, 7, 'seven') t2 = bst.insert(t2, 8, 'eight') t_list = bst.inorder_list(t2) # print(t_list) t2 = bst.delete(t2, 1) t2 = bst.delete(t2, 2) t2 = bst.delete(t2, 3) t2 = bst.delete(t2, 4) t2 = bst.delete(t2, 5) t_list = bst.inorder_list(t2) self.assertEqual(t_list, [0, 6, 7, 8, 9]) t2 = bst.delete(t2, 6) t2 = bst.delete(t2, 7) t2 = bst.delete(t2, 8) t2 = bst.delete(t2, 9) t2 = bst.delete(t2, 0) t_list = bst.inorder_list(t2) self.assertEqual(t_list, None)
def testHeight(): root = bst.Node(500) for i in range(1000): bst.insert(root, i, 0) print(bst.find(root, 199).height)
def insert(root, x): # assert root.is_valid node = bst.insert(root, x, is_nil=lambda x: x.is_nil) node.is_black = False fix_rbtree(node)
elif root.right is None: temp = root.left root = None return temp # Node with two children: Get the inorder successor # (smallest in the right subtree) temp = minValueNode(root.right) # Copy the inorder successor's content to this node root.val = temp.val # Delete the inorder successor root.right = deleteNode(root.right, temp.val) return root r = Node(50) insert(r, Node(30)) insert(r, Node(20)) insert(r, Node(40)) insert(r, Node(70)) insert(r, Node(60)) insert(r, Node(80)) # Uncomment to test # inorder(r) # print("*****") # deleteNode(r,30) # inorder(r)
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))
''' ''' def get_smallest(node): while (True): if(node.left == None): return node else: node = node.left ''' ''' root = None root = insert(root, 1) root = insert(root, 3) root = insert(root, 5) root = insert(root, 14) root = insert(root, 2) root = insert(root, 6) print get_successor(search(root, 2)).key # should print 5 ''' ''' find_intersection: finds an intersection of the given line segments, or decides that there is no intersection
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")
from __future__ import print_function import numpy as np import bst from bst import BinarySearchTree bst = BinarySearchTree() rand_ints = np.random.randint(1,100,100).tolist() print("Unsorted array: {0}".format(rand_ints)) print("Inserting 100 random integers into bst") [bst.insert(i) for i in rand_ints] print("bst is empty: {0}".format(bst.isEmpty())) print("Traversing bst in order:") bst.traverse_in_order() print("bst minimum: {0}".format(bst.min())) print("bst maximum: {0}".format(bst.max()))
The deleted node with key k. """ node = super(AVL, self).delete(k) ## node.parent is actually the old parent of the node, ## which is the first potentially out-of-balance node. self.rebalance(node.parent) def inorder(self): if self.root is None: print("<empty tree>") else: return self and super(AVL, self).inorder() print("\n") # def test(args=None): # bst.test(args, BSTtype=AVL) # if __name__ == '__main__': test() bst = AVL() n = int(input()) arr = list(map(int, input().split())) for i in range(n): bst.insert(arr[i]) # print(bst) print() bst.inorder()
from __future__ import print_function import numpy as np import bst from bst import BinarySearchTree bst = BinarySearchTree() rand_ints = np.random.randint(1, 100, 100).tolist() print("Unsorted array: {0}".format(rand_ints)) print("Inserting 100 random integers into bst") [bst.insert(i) for i in rand_ints] print("bst is empty: {0}".format(bst.isEmpty())) print("Traversing bst in order:") bst.traverse_in_order() print("bst minimum: {0}".format(bst.min())) print("bst maximum: {0}".format(bst.max()))