def dijkstra_shortest_path(self, start_vetex):
        """
        Find the shortest distance from a starting vertex to all other vertices.

        Keyword arguments:
        start_vertex -- a vertex object.

        Time complexity:
        O(VLogV + ELogV)

        Space complexity:
        O(V)
        """

        unvisited_queue = PriorityQueue(self.size, lambda el: el.distance,
                                        lambda el: el.data)

        # Set all vertices to a distance of infinity and a previous vertex
        # of None. Set the start_vertex's distance to 0.
        for vertex in self.adjacency_list:
            vertex.distance = float('inf')
            vertex.previous_vertex = None
            if vertex == start_vetex:
                vertex.distance = 0
            unvisited_queue.push(vertex)

        # Time complexity: O(V)
        while not unvisited_queue.is_empty():

            # Time complexity: O(LogV)
            current_vertex = unvisited_queue.pop()

            # Go through each of the current_vertex's adjacent vertices checking
            # to see if the path from the current vertex is shorter than the
            # previously found paths.
            # Time complexity: O(E)
            for adjacent_vertex in self.adjacency_list[current_vertex]:

                edge_weight = self.edge_weights[(current_vertex,
                                                 adjacent_vertex)]
                new_distance = current_vertex.distance + edge_weight

                # If a shorter path is found, update the adjacent vertex's distance
                # to the new distance and set it's previous pointer to the
                # current vertex.
                if new_distance < adjacent_vertex.distance:
                    adjacent_vertex.distance = new_distance
                    adjacent_vertex.previous_vertex = current_vertex

                    # Time complexity: O(LogV)
                    unvisited_queue.update_priority(adjacent_vertex)
class ExperimentIterator(object):

    def __init__(self, elements):
        """

        :param elements: list
        """
        self.pq = PriorityQueue()
        map(lambda (i, elem): self.pq.push(elem, i), enumerate(reversed(elements)))

    def next(self):
        try:
            return self.pq.pop()
        except:
            raise StopIteration

    def __iter__(self):
        return self
Example #3
0
 def test_push_pop(self):
     pq = PriorityQueue(lambda i: i.__key__(), [])
     pq.push(Item(5))
     pq.push(Item(1))
     pq.push(Item(3))
     self.assertEqual(pq.pop().x, 1)