Exemplo n.º 1
0
def test_empty_heap_creation():
    heap = IndexedHeap()
    assert len(heap) == 0, 'The length should be equal to 0'
    assert len(heap) == len(
        list(heap),
    ), 'The length should be exact as the number of the stored elements'
    assert heap.pop_first() == (None, None), 'Pop oeration should return None'
Exemplo n.º 2
0
def dijkstra_shortest_paths(adj_list, node_from, infinity_value=0xFFFFFFFF):
    distances = {k: infinity_value for k in get_nodes(adj_list)}
    distances[node_from] = 0

    visit_queue = IndexedHeap(distances)

    next_edge, distance = visit_queue.pop_first()
    while next_edge is not None:
        for edge in get_edges_from(adj_list, next_edge):
            if edge[0] in visit_queue and (distances[edge[0]] >
                                           distance + edge[1]):
                distances[edge[0]] = distance + edge[1]
                visit_queue.update({edge[0]: distances[edge[0]]})
        next_edge, distance = visit_queue.pop_first()

    return distances
Exemplo n.º 3
0
def test_heap_reversed_order():
    test_values = {1: 4, 2: 2, 4: 1, 5: 5}
    heap = IndexedHeap(test_values, reverse=True)

    assert is_heap(
        list(heap),
        start_position=0,
        compare_fn=lambda first, second: first[1] >= second[1],
    ), 'Max heap should be created'

    assert (
        heap.pop_first(),
        heap.pop_first(),
        heap.pop_first(),
        heap.pop_first(),
    ) == (
        (5, 5), (1, 4), (2, 2), (4, 1)  
    ), 'The items should be poped in sorted order'
Exemplo n.º 4
0
def test_heap_default_order():
    test_values = {1: 4, 2: 2, 3: 3, 4: 1, 5: 5}

    heap = IndexedHeap(test_values)
    assert is_heap(
        list(heap),
        start_position=0,
        compare_fn=lambda first, second: first[1] <= second[1],
    ), 'Min heap should be created by default'

    assert (
        heap.pop_first(),
        heap.pop_first(),
        heap.pop_first(),
        heap.pop_first(),
        heap.pop_first(),
    ) == (
        (4, 1), (2, 2), (3, 3), (1, 4), (5, 5),
    ), 'The items should be poped in sorted order'