예제 #1
0
    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
예제 #2
0
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
예제 #3
0
 def delete(self, key):
     """deletes a key and its associated value from tree, calls delete function in bst.py
     Args:
         key (*) : a key which is compareable by <,>,==
     """
     self.tree = bst.delete(self.tree, key)
     self.num_items -= 1
예제 #4
0
    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)
예제 #5
0
    def delete(self, key):
        """Removes a BSTNode from the tree map with the corresponding key.
        Calls delete function in bst.py

        Args:
            key (str) : the key (last name).
        """
        self.tree = delete(self.tree, key)
예제 #6
0
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)
예제 #7
0
 def delete(self, key):
     """Write the docstring
     Args:
         key (any) : a key which is compareable by <,>,==
     """
     #call a function in the bst module
     #and decrement the num_items
     self.tree = bst.delete(self.tree, key)
     self.num_items -= 1
예제 #8
0
 def delete(self, key):
     """Removes the key/value pair from the tree
     Args:
         key (any) : a key which is compareable by <,>,==
     Raises:
         KeyError : if the key does not exist
     """
     self.tree = bst.delete(self.tree, key)
     self.num_items -= 1
예제 #9
0
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
예제 #10
0
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
예제 #11
0
def test_deletion(tree_and_inserted, data):
    tree, inserted_keys = tree_and_inserted
    assume(len(inserted_keys) > 0)

    # Pick something to delete
    to_delete = data.draw(nodes_to_delete(tree), label="Nodes to delete")
    keys_to_delete = [node.key for node in to_delete]

    for node in to_delete:
        tree = delete(tree, node)

    assert_bst_property_holds(tree)
    keys_after_delete = [node.key for node in collect(tree)]

    # assert len(inserted_keys) - len(keys_after_delete) == len(keys_to_delete)

    kept_keys = set(inserted_keys) - set(keys_to_delete)

    for kept_key in kept_keys:
        assert kept_key in keys_after_delete

    for deleted_key in keys_to_delete:
        # assert deleted_key not in keys_after_delete
        pass
예제 #12
0
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")
예제 #13
0
    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)