コード例 #1
0
def dijkstra_directed(graph, start):
    """
    Arguments: <graph> is a graph object, where edges have integer <weight>
        attributes,	and <start> is a vertex of <graph>.
    Action: Uses Dijkstra's algorithm to compute all vertex distances
        from <start> in <graph>, and assigns these values to the vertex attribute <dist>.
        Optional: assigns the vertex attribute <in_edge> to be the incoming
        shortest path edge, for every reachable vertex except <start>.
        <graph> is viewed as a directed graph.
    """
    # Initialize the vertex attributes:
    init_search(graph, start)
    min_heap = Heap(len(graph.vertices))

    for vertica in graph.vertices:
        min_heap += vertica

    # print(min_heap, len(min_heap))
    while min_heap:
        v = min_heap.pop()
        # print(f"Just popped: {v, v.dist}")
        # print(len(min_heap), min_heap)
        for edge in filter(lambda e: e.tail == v, v.incidence):
            if edge.weight < 0:
                show_warning_dijkstra(edge)
            # print(f"Before:{edge, edge.tail.dist, edge.head.dist, edge.weight}")
            edge_relaxed(edge, True, start, min_heap)
コード例 #2
0
    def test_max_heap(self):
        arr = [5, 1, 6, 9, 72, 42, 51]
        heap = Heap(Heap.Type.MAX, arr.copy())

        arr.sort()

        for i in range(len(arr)-1, -1, -1):
            expected = arr[i]
            actual = heap.pop()
            # print(f'expected: {expected}, actual: {actual}')
            self.assertEqual(expected, actual)
コード例 #3
0
def dijkstra_undirected(graph: "Graph", start: "Vertex"):
    """
    Arguments: <graph> is a graph object, where edges have integer <weight>
        attributes,	and <start> is a vertex of <graph>.
    Action: Uses Dijkstra's algorithm to compute all vertex distances
        from <start> in <graph>, and assigns these values to the vertex attribute <dist>.
        Optional: assigns the vertex attribute <in_edge> to be the incoming
        shortest path edge, for every reachable vertex except <start>.
        <graph> is viewed as an undirected graph.
    """
    # Initialize the vertex attributes:
    init_search(graph, start)
    min_heap = Heap(len(graph.vertices))

    for vertica in graph.vertices:
        min_heap += vertica

    while min_heap:
        # print(min_heap.count)
        v = min_heap.pop()
        for edge in v.incidence:
            if edge.weight < 0:
                show_warning_dijkstra(edge)
            edge_relaxed(edge, False, start, min_heap)
コード例 #4
0
def short_path(graph, start, end):
    processed = set()
    processed.add(start)

    shortest_path = defaultdict(lambda: float('inf'))
    predecessor = defaultdict(list)
    shortest_path[start] = 0

    heap = Heap(graph[start])

    while len(processed) < len(graph):
        w_star, w_star_dis = heap.pop(with_key=True)
        shortest_path[w_star] = w_star_dis

        for v, v_dis in graph[w_star]:
            if v in processed: continue

            try:
                key_v = heap.pop(key=v)
            except KeyError:
                key_v = float('inf')

            key_v = min(key_v, shortest_path[w_star] + v_dis)

            heap.insert((v, key_v))

        processed.add(w_star)
        predecessor[end].append(w_star)

        # v_w_pair = []
        # for v in processed:
        #     v_w_pair += [(v, w, shortest_path[v] + dis_w) for w, dis_w in graph[v] if w not in processed]
        #
        # v_star, w_star, w_star_dis = min(v_w_pair, key=lambda x: x[2])
        #
        # processed.add(w_star)
        # shortest_path[w_star] = w_star_dis
        # predecessor[w_star] = predecessor[v_star] + [w_star]

        if w_star == end: break

    return shortest_path[end], predecessor[end]
コード例 #5
0
from heap.heap import Heap

arr = [10, 5, 3, 2, 4]
heap = Heap(arr, "max")
print(heap)

heap.push(15)
print(heap)

heap.pop()
print(heap)

heap.remove(3)
print(heap)

heap.push(7)
print(heap)

heap.push(8)
print(heap)

print(heap.peek())
コード例 #6
0
from heap.heap import Heap

h = Heap(10)
h.insert('A')
h.insert('B')
h.insert('C')
h.insert('D')
h.insert('E')
h.insert('F')
h.insert('G')

while True:
    ret = h.delete_max()
    if ret is None:
        break
    print(ret, end=' ')