Example #1
0
def test_insert_into_heap():
    heap = Heap([8, 5, 2, 4, 3, 1])
    heap.insert(6)

    expected = [0, 8, 5, 6, 4, 3, 1, 2]
    output = heap.heap
    assert output == expected
Example #2
0
def test_insert_empty_heap():
    heap = Heap()
    heap.insert(4)

    expected = [0, 4]
    output = heap.heap
    assert output == expected
Example #3
0
 def test_bubble_down(self):
     h = Heap([])
     h.data = [3, 2, 4]
     new_index = h.bubble_down(0)
     self.assertTrue(Heap.is_heap(h.data), 'should maintain the heap prop')
     self.assertEqual(h.data, [2, 3, 4], 'should have reorganized the heap')
     self.assertEqual(new_index, 1, 'should return the correct new index')
Example #4
0
def test_delete_from_one_element_heap():
    heap = Heap([1])
    heap.delete()

    expected = [0]
    output = heap.heap
    assert output == expected
Example #5
0
 def test_bubble_down(self):
     h = Heap([])
     h.data = [3, 2, 4]
     new_index = h.bubble_down(0)
     self.assertTrue(Heap.is_heap(h.data), 'should maintain the heap prop')
     self.assertEqual(h.data, [2,3,4], 'should have reorganized the heap')
     self.assertEqual(new_index, 1, 'should return the correct new index')
Example #6
0
    def test_append_0(self):
        h = Heap()

        h.append(42)

        assert h
        assert h[0] == 42
Example #7
0
def test_delete_from_empty_heap():
    heap = Heap()
    heap.delete()

    expected = [0]
    output = heap.heap
    assert output == expected
Example #8
0
def test_insert_empty_heap_two_elements():
    heap = Heap()
    heap.insert(1)
    heap.insert(3)

    expected = [0, 3, 1]
    output = heap.heap
    assert output == expected
Example #9
0
def test_delete_from_full_heap():
    heap = Heap([9, 7, 5, 6, 2])
    deleted_node = heap.delete()

    expected = [0, 7, 6, 5, 2]
    output = heap.heap
    assert output == expected
    assert deleted_node == 9
Example #10
0
def test_delete_from_two_element_heap():
    heap = Heap([5, 1])
    deleted_node = heap.delete()

    expected = [0, 1]
    output = heap.heap
    assert output == expected
    assert deleted_node == 5
Example #11
0
def test_heap_pop_big_list():
    from src.heap import Heap
    big_list = [
        1, 9, 6, 2, 3, 7, 4, 5, 9, 1, 2, 5, 4, 6, 8, 7, 2, 3, 4, 9, 8, 7, 6, 1,
        3, 4, 6, 7, 9, 0, 1
    ]
    test_heap = Heap(big_list)
    test_value = test_heap.pop()
    assert test_value == max(big_list)
Example #12
0
    def test_static_is_heap(self):
        """ Tests static method is_heap if it can correctly verify if a
        list of elements preserves the heap property.
        """
        good = [4, 4, 8, 9, 4, 12, 9, 11, 13]
        bad = [1,2,3,114,5,6,7,8,9,10]

        self.assertTrue(Heap.is_heap(good), 'should hold the heap property')
        self.assertFalse(Heap.is_heap(bad), 'should not hold the heap property')
Example #13
0
    def test_append_2(self, N=10):
        h = Heap()

        for i in range(N):
            h.append(i)

        assert h
        for i in range(N):
            assert h[i] == i
Example #14
0
    def test_append_1(self):
        h = Heap()

        h.append(42)
        h.append(43)

        assert h
        assert h[0] == 42
        assert h[1] == 43
Example #15
0
    def test_pop_1(self):
        h = Heap()

        h.append(42)

        t = h.pop()

        assert t == 42
        assert not h
Example #16
0
    def test_static_is_heap(self):
        """ Tests static method is_heap if it can correctly verify if a
        list of elements preserves the heap property.
        """
        good = [4, 4, 8, 9, 4, 12, 9, 11, 13]
        bad = [1, 2, 3, 114, 5, 6, 7, 8, 9, 10]

        self.assertTrue(Heap.is_heap(good), 'should hold the heap property')
        self.assertFalse(Heap.is_heap(bad),
                         'should not hold the heap property')
Example #17
0
    def test_heap_sort_1(self, N=1000, fst=-1024, lst=1024):
        xs = [random.randint(fst, lst) for i in range(N)]

        ys = xs.copy()

        h = Heap(xs, reverse=True)

        h.sort()

        assert h.xs == sorted(ys)
Example #18
0
    def test_pop_2(self, N=10):
        h = Heap()

        for i in range(N):
            h.append(i)

        assert len(h) == N
        for i in range(N):
            assert i == h.pop()
        assert not h
Example #19
0
    def test_pop_3(self, N=10):
        h = Heap()

        for i in range(N):
            h.append(i)

        assert len(h) == N
        for i in reversed(range(N)):
            assert i == N - 1 - h.pop()
        assert not h
Example #20
0
def heap_sort(values: List[int]) -> List[int]:
    heap = Heap()
    sorted_values = []
    for value in values:
        heap.insert(f'node_{value}', value)
    while len(sorted_values) < len(values):
        name, value = heap.pop_min()
        sorted_values.append(value)

    return sorted_values
Example #21
0
    def test_extract_min(self):
        """ Makes sure that the heap produces min values and that
        the heap property is preserved.
        Given the following heap:
                        (4)
                       /   \
                    (4)    (8)
                   /  \    /  \
                 (9) (4) (12) (9)
                /  \
             (11)  (13)
        """
        data = [4, 4, 8, 9, 4, 12, 9, 11, 13]
        h = Heap(data)

        min_key = h.extract_min()
        self.assertEqual(min_key, 4, 'should extract the min value')
        self.assertTrue(Heap.is_heap(data),
                        'should still hold the heap property')

        min_key = h.extract_min()
        self.assertEqual(min_key, 4, 'should extract the min value')
        self.assertTrue(Heap.is_heap(data),
                        'should still hold the heap property')

        min_key = h.extract_min()
        self.assertEqual(min_key, 4, 'should extract the min value')
        self.assertTrue(Heap.is_heap(data),
                        'should still hold the heap property')
Example #22
0
    def test_get_min(self):
        h = Heap(range(10))

        min_index = h.get_min(2, 4, 6)
        self.assertEqual(min_index, 2, 'should return the index with the min key')

        min_index = h.get_min(6, 4, 2)
        self.assertEqual(min_index, 2, 'should return the index with the min key')

        min_index = h.get_min(4, 2, 6)
        self.assertEqual(min_index, 2, 'should return the index with the min key')

        min_index = h.get_min(4, 2, 100)
        self.assertEqual(min_index, 2, 'should work for unknown indexes')
Example #23
0
    def __dijkstra(self, grafo, origen, visitados, pesos, pv):
        #c = Cola()
        c = Heap()

        visitados[origen.getPosicion()] = True

        c.poner(0, origen)

        while not c.esVacia():
            proximo = c.sacar()

            for i in proximo.getListaAdyacentes():
                peso_actual = pesos[i.getVerticeDestino().getPosicion()]
                if peso_actual is None:
                    nuevo_peso =  i.getPeso()
                    peso_actual = nuevo_peso + 1
                else:
                    nuevo_peso = peso_actual + i.getPeso()

                if nuevo_peso < peso_actual:
                    pesos[i.getVerticeDestino().getPosicion()] = nuevo_peso
                    pv[i.getVerticeDestino().getPosicion()] = proximo

                if not visitados[i.getVerticeDestino().getPosicion()]:
                    c.poner(i.getPeso(), i.getVerticeDestino())
                    visitados[i.getVerticeDestino().getPosicion()] = True

        return pv
Example #24
0
def test_heapify_list_with_two_elements():
    list_to_heapify = [1, 3]
    heap = Heap(list_to_heapify)

    expected = [0, 3, 1]
    output = heap.heap
    assert output == expected
Example #25
0
def test_heapify_full_list():
    list_to_heapify = [3, 1, 7, 4]
    heap = Heap(list_to_heapify)

    expected = [0, 7, 4, 3, 1]
    output = heap.heap
    assert output == expected
Example #26
0
def test_heapify_larger_list():
    list_to_heapify = [1, 9, 7, 4, 3, 8]
    heap = Heap(list_to_heapify)

    expected = [0, 9, 4, 8, 1, 3, 7]
    output = heap.heap
    assert output == expected
Example #27
0
def test_heapify_heap_list():
    list_to_heapify = [9, 4, 8, 1, 3, 7]
    heap = Heap(list_to_heapify)

    expected = [0, 9, 4, 8, 1, 3, 7]
    output = heap.heap
    assert output == expected
Example #28
0
def k_sorted_array(arr, k):
    """ Method sorts a k-sorted array.

    A k-sorted array is an array where each element is at most k positions away
    of it's final sorted position.

    This solution piggybacks on the heapsort algorithm

    Complexity: O(nlogk) in time

    Args:
        arr: list, of values to sort.
        k: int, the max distance any element can be from it's final sorted position.

    Returns:
        list, sorted array
    """
    n = len(arr)
    if n < k:
        k = n

    heap = Heap.heapify(arr[:k])

    out = []
    for i in range(k, n):
        min_value = heap.extract_min_and_insert(arr[i])
        out.append(min_value)

    for i in range(k):
        min_value = heap.extract_min()
        out.append(min_value)

    return out
Example #29
0
 def test_init(self, input_nodes, expected_nodes, expected_index):
     """
     testing the init also allows to test the heapify up
     """
     new_heap = Heap(input_nodes)
     assert new_heap.nodes == expected_nodes
     assert new_heap.index == expected_index
Example #30
0
def test_heapify_empty_list():
    list_to_heapify = []
    heap = Heap(list_to_heapify)

    expected = [0]
    output = heap.heap
    assert output == expected
Example #31
0
    def remove(self, vertex):
        """ Overrides parent method to remove a vertex by it's vertex not cost.

        Args
            vertex: str, name of the vertex to remove.
        """
        index = map(itemgetter(0), self.data).index(vertex)
        return Heap.remove(self, index)
Example #32
0
    def test_remove(self):
        """ Test the removal of a key from the middle of the heap.
        Given the following heap:
                        (4)
                       /   \
                    (4)    (8)
                   /  \    /  \
                 (9) (4) (12) (9)
                /  \
             (11)  (13)
        """
        data = [4, 4, 8, 9, 4, 12, 9, 11, 13]
        h = Heap(data)
        h.remove(2)

        self.assertTrue(Heap.is_heap(data), 'should preserve heap property')
        self.assertNotIn(8, h.data, 'the value corresponding to the index was removed')
Example #33
0
    def test_extract_min(self):
        """ Makes sure that the heap produces min values and that
        the heap property is preserved.
        Given the following heap:
                        (4)
                       /   \
                    (4)    (8)
                   /  \    /  \
                 (9) (4) (12) (9)
                /  \
             (11)  (13)
        """
        data = [4, 4, 8, 9, 4, 12, 9, 11, 13]
        h = Heap(data)

        min_key = h.extract_min()
        self.assertEqual(min_key, 4, 'should extract the min value')
        self.assertTrue(Heap.is_heap(data), 'should still hold the heap property')

        min_key = h.extract_min()
        self.assertEqual(min_key, 4, 'should extract the min value')
        self.assertTrue(Heap.is_heap(data), 'should still hold the heap property')

        min_key = h.extract_min()
        self.assertEqual(min_key, 4, 'should extract the min value')
        self.assertTrue(Heap.is_heap(data), 'should still hold the heap property')
Example #34
0
    def test_remove(self):
        """ Test the removal of a key from the middle of the heap.
        Given the following heap:
                        (4)
                       /   \
                    (4)    (8)
                   /  \    /  \
                 (9) (4) (12) (9)
                /  \
             (11)  (13)
        """
        data = [4, 4, 8, 9, 4, 12, 9, 11, 13]
        h = Heap(data)
        h.remove(2)

        self.assertTrue(Heap.is_heap(data), 'should preserve heap property')
        self.assertNotIn(8, h.data,
                         'the value corresponding to the index was removed')
Example #35
0
    def test_extract_min_and_insert(self):
        """ Test if extracting min and adding a new value at the same time works.
        Given the following heap:
                        (4)
                       /   \
                    (5)    (8)
                   /  \    /  \
                 (9) (6) (12) (9)
                /  \
             (11)  (13)
        """
        data = [4, 5, 8, 9, 6, 12, 9, 11, 13]
        h = Heap(data)

        min_value = h.extract_min_and_insert(2)
        self.assertEqual(min_value, 4, 'should return the min value')
        expected = [2, 5, 8, 9, 6, 12, 9, 11, 13]
        self.assertEqual(h.data, expected, 'should remove the old min and '+
                                           'add new value correctly')
Example #36
0
    def test_extract_min_and_insert(self):
        """ Test if extracting min and adding a new value at the same time works.
        Given the following heap:
                        (4)
                       /   \
                    (5)    (8)
                   /  \    /  \
                 (9) (6) (12) (9)
                /  \
             (11)  (13)
        """
        data = [4, 5, 8, 9, 6, 12, 9, 11, 13]
        h = Heap(data)

        min_value = h.extract_min_and_insert(2)
        self.assertEqual(min_value, 4, 'should return the min value')
        expected = [2, 5, 8, 9, 6, 12, 9, 11, 13]
        self.assertEqual(
            h.data, expected,
            'should remove the old min and ' + 'add new value correctly')
Example #37
0
    def test_insert(self):
        """ Test that adding an element preserves the heap property.
        Given the following heap:
                        (4)
                       /   \
                    (4)    (8)
                   /  \    /  \
                 (9) (4) (12) (9)
                /  \
             (11)  (13)
        """
        data = [4, 4, 8, 9, 4, 12, 9, 11, 13]
        h = Heap(data)

        h.insert(7)
        self.assertTrue(Heap.is_heap(h.data), 'should still be a heap')

        h.insert(10)
        self.assertTrue(Heap.is_heap(h.data), 'should still be a heap')

        h.insert(5)
        self.assertTrue(Heap.is_heap(h.data), 'should still be a heap')
Example #38
0
    def dijkstra(self, node_key: str,
                 node_destination_key: str) -> List[Tuple[str, int]]:
        """
        Method that returns the shortest path between 2 nodes

        We will store for each node its parent(previous_node)
        We will store the distances from source node in a distances registry

        1. At first the distance registry is set to infinite except for the source node
        2. We will use a heap, in which we temporarily store the nodes to visit
        3. The heap will allow us to retrieve the next node with minimal distance from source node
        4. From each visited nodes, we will store its neighbors in the heap,
           and if the distance we found is shorter than the previous one,
           we update the distance and store it in the heap to be visited.
        5. Finally, from the destination key, we will look in the parent registry,
           and create the path with the distance registry
        """
        heap_instance = Heap()
        # set the distances registry
        distances = {}
        visited = []
        previous_node = {}
        for key in self.nodes.keys():
            distances[key] = cmath.inf
        distances[node_key] = 0
        # helper to create path
        previous_node[node_key] = None
        heap_instance.insert(node_key, 0)
        while len(heap_instance.nodes) > 0:
            heap_node = heap_instance.pop_min()
            current_key = heap_node[0]
            visited.append(current_key)
            for child_key, child_value in self.nodes[current_key].items():
                if child_key in visited:
                    continue
                # At first we have zero, then we take this value and we update it(so we don't deal with inf)
                new_dist = distances[current_key] + child_value
                if new_dist < distances[child_key]:
                    distances[child_key] = new_dist
                    heap_instance.insert(child_key, new_dist)
                    previous_node[child_key] = current_key

        key = node_destination_key
        path = []
        while previous_node[key]:
            path.insert(0, (key, distances[key]))
            key = previous_node[key]
        path.insert(0, (node_key, 0))

        return path
Example #39
0
    def test_problem_1(self):
        """ You are given as input an unsorted array of n distinct numbers,
        where n is a power of 2. Give an algorithm that identifies the
        second-largest number in the array, and that uses at most
        n+log2n−2 comparisons.

        Solution: use a hash data structure.
        """
        numbers = [
            5, 1, 2, 5, 1, 2, 3, 54, 6, 7, 1, 3, 3, 5, 6, 2, 3, 4, 56, 6
        ]
        h = Heap()
        for number in numbers:
            h.insert(-number)

        h.extract_min()
        actual = -h.extract_min()
        self.assertEqual(actual, 54, 'found the second largest number')
Example #40
0
    def test_problem_1(self):
        """ You are given as input an unsorted array of n distinct numbers,
        where n is a power of 2. Give an algorithm that identifies the
        second-largest number in the array, and that uses at most
        n+log2n−2 comparisons.

        Solution: use a hash data structure.
        """
        numbers = [5,1,2,5,1,2,3,54,6,7,1,3,3,5,6,2,3,4,56,6]
        h = Heap()
        for number in numbers:
            h.insert(-number)

        h.extract_min()
        actual = -h.extract_min()
        self.assertEqual(actual, 54, 'found the second largest number')
Example #41
0
    def test_get_min(self):
        h = Heap(range(10))

        min_index = h.get_min(2, 4, 6)
        self.assertEqual(min_index, 2,
                         'should return the index with the min key')

        min_index = h.get_min(6, 4, 2)
        self.assertEqual(min_index, 2,
                         'should return the index with the min key')

        min_index = h.get_min(4, 2, 6)
        self.assertEqual(min_index, 2,
                         'should return the index with the min key')

        min_index = h.get_min(4, 2, 100)
        self.assertEqual(min_index, 2, 'should work for unknown indexes')
def find_rectangle_candidates(
        cutout: np.array,
        points: np.array,
        candidate_limit: int = 20) -> List[Tuple[np.array]]:
    """Returns a list of rectangles with maximum space overlap with original figure."""
    heap = Heap()
    for quad in tqdm(combinations(points, 4),
                     total=num_combinations(len(points), 4)):
        zeros = np.zeros_like(cutout)
        for p in quad:
            zeros[p[0], p[1]] = 1
        chull = convex_hull_image(zeros)
        space_part = np.sum(chull * cutout)
        heap.insert((space_part, quad))
    best_space, _ = heap.peek()
    retlist = []
    total = 0
    while total < candidate_limit and heap.peek()[0] >= 0.9 * best_space:
        space, cur_points = heap.pop()
        retlist.append(cur_points)
    return retlist
Example #43
0
def test_heap_pop_big_list():
    from src.heap import Heap
    big_list = [1,9,6,2,3,7,4,5,9,1,2,5,4,6,8,7,2,3,4,9,8,7,6,1,3,4,6,7,9,0,1]
    test_heap = Heap(big_list)
    test_value = test_heap.pop()
    assert test_value == max(big_list)
Example #44
0
def test_heap_push2():
    from src.heap import Heap
    test_heap = Heap()
    test_heap.push(1)
    test_heap.push(3)
    assert test_heap.root == 3
Example #45
0
 def __init__(self, data=None):
     Heap.__init__(self, data)
Example #46
0
 def test_remove_if_index_is_root(self):
     data = [3, 4, 5]
     h = Heap(data)
     h.remove(0)
     self.assertEqual(h.data, [4,5], 'should remove the root')
     self.assertTrue(Heap.is_heap(h.data), 'should maintain heap invariant')
Example #47
0
 def test_remove_if_index_is_last(self):
     data = [3, 4, 5]
     h = Heap(data)
     h.remove(2)
     self.assertEqual(h.data, [3, 4], 'should remove the last leaf')
     self.assertTrue(Heap.is_heap(h.data), 'should maintain heap invariant')
Example #48
0
 def test_remove_if_one_element(self):
     data = [3]
     h = Heap(data)
     h.remove(0)
     self.assertEqual(h.data, [], 'should remove the only elem in heap')
     self.assertTrue(Heap.is_heap(h.data), 'should maintain heap invariant')
Example #49
0
def test_heap_pop_root_is_maxval():
    from src.heap import Heap
    test_heap = Heap([2,4,6])
    test_value = test_heap.pop()
    assert test_value >= max(test_heap.heapList[1:])
Example #50
0
def test_heap_pop_removed():
    from src.heap import Heap
    test_heap = Heap([2, 4, 6])
    test_value = test_heap.pop()
    assert test_value not in test_heap.heapList
Example #51
0
    def test_heap_sort_raises(self):
        h = Heap()

        with pytest.raises(RuntimeError):
            h.sort()
Example #52
0
def test_heap_pop_simple():
    from src.heap import Heap
    test_heap = Heap([2,4,6])
    test_value = test_heap.root
    assert test_heap.pop() == test_value 
Example #53
0
def test_heap_pop_didnt_kill_list():
    from src.heap import Heap
    test_heap = Heap([2, 4, 6])
    test_value = test_heap.pop()
    assert len(test_heap.heapList) == 3
Example #54
0
 def test_heap_length(self):
     data = [1,2,3,114,5,6,7,8,9,10]
     h = Heap.heapify(data)
     self.assertEqual(len(h), len(data), 'should be the same length')
Example #55
0
def test_heap_push2():
    from src.heap import Heap
    test_heap = Heap()
    test_heap.push(1)
    test_heap.push(3)
    assert test_heap.root == 3
Example #56
0
 def test_static_heapify(self):
     data = [8,2,6,3,1,2,9,5,3,7,4]
     h = Heap.heapify(data)
     self.assertTrue(Heap.is_heap(data), 'should preserve heap property')
Example #57
0
def test_heap_pop_didnt_kill_list():
    from src.heap import Heap
    test_heap = Heap([2,4,6])
    test_value = test_heap.pop()
    assert len(test_heap.heapList) == 3
Example #58
0
def test_heap_pop_removed():
    from src.heap import Heap
    test_heap = Heap([2,4,6])
    test_value = test_heap.pop()
    assert test_value not in test_heap.heapList