Example #1
0
def test_find_root():
    heap = Heap()
    items = [KeyedItem(key=i) for i in range(10)]
    random_items = [item for item in items]
    random.shuffle(random_items)
    heap.heapify(random_items)
    assert heap.find_root() is items[0]
def heapsort(items: Sequence[KeyedItem], order=None) -> List[KeyedItem]:
    """O(n*log n)"""
    heap = Heap(heaptype=order)
    heap.heapify(items)
    sorted_items = []
    while True:
        item = heap.extract_root()
        if not item:
            break
        sorted_items.append(item)
    return sorted_items
Example #3
0
def test_delete_last():
    heap = Heap()
    items = [KeyedItem(key=i) for i in range(10)]
    heap.heapify(items)
    heap.delete(items[9])
    for i in range(9):
        assert heap.extract_root() is items[i]
    assert heap.extract_root() is None
Example #4
0
def test_delete_root():
    heap = Heap()
    items = [KeyedItem(key=i) for i in range(10)]
    random_items = [item for item in items]
    random.shuffle(random_items)
    heap.heapify(random_items)
    heap.delete(items[0])
    for i in range(1, 10):
        assert heap.extract_root() is items[i]
    assert heap.extract_root() is None
Example #5
0
 def test_push(self):
     stack = Heap()
     stack.push(4)
     stack.push(5)
     stack.push(1)
     stack.push(2)
     self.assertEqual(stack.pop(), 1)
Example #6
0
def test_delete_with_bubble_down():
    heap = Heap()
    items_keys = list(range(5)) + list(range(100, 112))
    items = [KeyedItem(key=i) for i in items_keys]
    heap.heapify(items)
    heap.delete(items[5])
    for i in range(17):
        if i != 5:
            root = heap.extract_root()
            assert root is items[i]
    assert heap.extract_root() is None
Example #7
0
def heapsort(arr: List):
    heap = Heap(arr)
    heap.build_max_heap()
    for i in reversed(range(1, heap.heap_size)):
        heap[0], heap[i] = heap[i], heap[0]
        heap.heap_size -= 1
        heap.max_heapify(0)
Example #8
0
    def setUp(self) -> None:
        list_1 = [1, 6, 2, 2, 23, 54, 43]
        list_2 = [1]
        list_3 = [5, 3, 2]

        self.data_we_want_sorted = Heap(list_1)
        self.single_item_heap = Heap(list_2)
        self.three_item_heap = Heap(list_3)
Example #9
0
def test_construct_max_heap():
    heap = Heap(heaptype='max')
    items = [KeyedItem(key=i) for i in range(10)]
    random_items = [item for item in items]
    random.shuffle(random_items)
    heap.heapify(random_items)
    for i in range(10):
        assert heap.extract_root() is items[10 - i - 1]
    assert heap.extract_root() is None
Example #10
0
def test_insert_min_heap():
    heap = Heap()
    items = [KeyedItem(key=i) for i in range(10)]
    random_items = [item for item in items]
    random.shuffle(random_items)
    for item in random_items:
        heap.insert(item)
    for i in range(10):
        assert heap.extract_root() is items[i]
    assert heap.extract_root() is None
Example #11
0
 def test_parent(self):
     self.assertEqual(0, Heap.par_index(1))
     self.assertEqual(1, Heap.par_index(3))
     self.assertEqual(0, Heap.par_index(0))
     self.assertEqual(2, Heap.par_index(5))
     self.assertEqual(2, Heap.par_index(6))
Example #12
0
def test_delete_only_item():
    heap = Heap()
    item = KeyedItem(key=0)
    heap.insert(item)
    heap.delete(item)
    assert heap.extract_root() is None
Example #13
0
class TestHeap(unittest.TestCase):

    data_we_want_sorted = single_item_heap = None

    # Method prepares the test fixture
    def setUp(self) -> None:
        list_1 = [1, 6, 2, 2, 23, 54, 43]
        list_2 = [1]
        list_3 = [5, 3, 2]

        self.data_we_want_sorted = Heap(list_1)
        self.single_item_heap = Heap(list_2)
        self.three_item_heap = Heap(list_3)

    def test_parent(self):
        self.assertEqual(0, Heap.par_index(1))
        self.assertEqual(1, Heap.par_index(3))
        self.assertEqual(0, Heap.par_index(0))
        self.assertEqual(2, Heap.par_index(5))
        self.assertEqual(2, Heap.par_index(6))

    def test_add(self):
        self.three_item_heap.add(1)
        self.assertEqual(len(self.three_item_heap), 4)
        self.assertEqual(self.three_item_heap.data, [5, 3, 2, 1])

    def test_remove(self):
        self.single_item_heap.remove()
        self.three_item_heap.remove(-1)
        self.assertEqual(self.single_item_heap.data, [])
        self.assertEqual(self.three_item_heap.data, [5, 3])

    def test_max_heapify(self):
        self.single_item_heap.max_heapify(0)
        self.assertEqual(self.single_item_heap.data, [1])
        self.single_item_heap.add(2)
        self.assertEqual(self.single_item_heap.data, [2, 1])

    def test_sort(self):
        sorted_data = [54, 43, 23, 6, 2, 2, 1]

        self.assertEqual(self.data_we_want_sorted.heapsort(), sorted_data)
        self.assertEqual(self.single_item_heap.heapsort(), [1])

    def tearDown(self) -> None:
        self.data_we_want_sorted = self.three_item_heap = self.single_item_heap = None
Example #14
0
 def test_empty(self):
     stack = Heap()
     self.assertTrue(stack.is_empty())
Example #15
0
def test_construct_empty_heap():
    heap = Heap()
    items = []
    heap.heapify(items)
    assert heap.extract_root() is None
Example #16
0
def run_dijkstra_algorithm(graph: Graph,
                           source: Vertex) -> NodeList:
    nb_processed_vertices = 1
    nb_vertices = graph.nb_vertices
    shortest_paths = NodeList(vertices=graph.adjacency_lists)

    # a list of vertices does the bookkeeping of keeping track
    # of which vertices are processed/unprocessed
    vertex_statuses = NodeList(vertices=graph.adjacency_lists,
                               default=False)

    class ItemContent:
        def __init__(self, vertex: Vertex, edge: Edge=None):
            self.vertex = vertex
            self.edge = edge

    class Path:
        def __init__(self, source: Vertex):
            self.source = source
            self.destination = None
            self.path_to_last_hop = None
            self.last_hop = None
            self.distance = None

        def build(self, path_to_last_hop, last_hop: Edge):
            if self.source is not path_to_last_hop.source:
                raise PathError
            if path_to_last_hop.destination is not last_hop.head:
                raise PathError
            self.path_to_last_hop = path_to_last_hop
            self.last_hop = last_hop
            self.destination = last_hop.tail
            self.distance = path_to_last_hop.distance + last_hop.weight

    # a heap contains all vertices not in the path
    # their keys are the min distance to the source vertex
    # initialization in O(n + m)
    heap = Heap(heaptype='min')
    for vertex in graph.adjacency_lists:
        shortest_paths[vertex] = Path(source=source)
        shortest_paths[vertex].distance = inf

    shortest_paths[source].destination = source
    shortest_paths[source].distance = 0

    for edgenode in graph.adjacency_lists[source].edgenodes:
        tail = edgenode.tail
        if edgenode.weight < 0:
            raise GraphTypeError
        if shortest_paths[tail].distance is not None and edgenode.weight < shortest_paths[tail].distance:
            shortest_paths[tail].destination = tail
            shortest_paths[tail].last_hop = edgenode.to_edge(head=source)
            shortest_paths[tail].distance = edgenode.weight

    vertex_items = []
    for vertex in graph.adjacency_lists:
        if vertex is not source:
            vertex_item = KeyedItem(key=shortest_paths[vertex].distance,
                                    content=ItemContent(vertex=vertex,
                                                        edge=shortest_paths[vertex].last_hop))
            vertex_items.append(vertex_item)
            vertex_statuses[vertex] = vertex_item

    heap.heapify(vertex_items)
    del vertex_items

    def update_heap(deleted_vertex: Vertex, distance_to_deleted_vertex: float):
        nonlocal graph, heap, vertex_statuses
        # update status
        vertex_statuses[deleted_vertex] = False
        # remove from the heap all vertices connected to
        # the deleted vertex
        for edgenode in graph.adjacency_lists[deleted_vertex].edgenodes:
            tail = edgenode.tail
            # check if the tail is in unprocessed vertices set
            vertex_item = vertex_statuses[tail]
            if vertex_item:
                distance = vertex_item.key
                vertex = vertex_item.content.vertex
                edge = vertex_item.content.edge
                # delete it from the heap
                heap.delete(vertex_item)
                # recompute its distance
                if edgenode.weight < 0:
                    raise GraphTypeError
                new_distance = distance_to_deleted_vertex + edgenode.weight
                if new_distance < distance:
                    distance = new_distance
                    edge = edgenode.to_edge(head=deleted_vertex)
                vertex_item.key = distance
                vertex_item.content = ItemContent(vertex=vertex, edge=edge)
                # insert it back into the heap
                heap.insert(vertex_item)

    while nb_processed_vertices < nb_vertices:
        # pick cheapest edge crossing the cut
        # from the graph shortest_path_tree = (processed_vertices, paths)
        # to the graph graph - shortest_path_tree
        heap_item = heap.extract_root()
        last_hop = heap_item.content.edge
        v = heap_item.content.vertex
        # add it to the path leading to v
        shortest_paths[v].build(path_to_last_hop=shortest_paths[last_hop.head],
                                last_hop=last_hop)
        # update nb_processed_vertices
        nb_processed_vertices += 1
        # update heap
        update_heap(deleted_vertex=v, distance_to_deleted_vertex=shortest_paths[v].distance)

    return shortest_paths
Example #17
0
def test_delete_with_bubble_up():
    heap = Heap()
    items_keys = (list(range(2)) + [100] + list(range(2, 4)) +
                  list(range(101, 103)) + list(range(4, 8)) +
                  list(range(103, 107)) + list(range(8, 10)))
    items = [KeyedItem(key=i) for i in items_keys]
    heap.heapify(items)
    heap.delete(items[5])
    for i in range(2):
        assert heap.extract_root() is items[i]
    for i in range(3, 5):
        assert heap.extract_root() is items[i]
    for i in range(7, 11):
        assert heap.extract_root() is items[i]
    for i in range(15, 17):
        assert heap.extract_root() is items[i]
    assert heap.extract_root() is items[2]
    assert heap.extract_root() is items[6]
    for i in range(11, 15):
        assert heap.extract_root() is items[i]
    assert heap.extract_root() is None
Example #18
0
 def test_emptyException(self):
     stack = Heap()
     with self.assertRaises(EmptyHeap) as context:
         stack.pop()
         self.assertTrue('Heap is empty', context.exception)