当前位置: 首页>>代码示例>>Python>>正文


Python PriorityQueue.remove_min方法代码示例

本文整理汇总了Python中priorityQueue.PriorityQueue.remove_min方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.remove_min方法的具体用法?Python PriorityQueue.remove_min怎么用?Python PriorityQueue.remove_min使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在priorityQueue.PriorityQueue的用法示例。


在下文中一共展示了PriorityQueue.remove_min方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Djikstraks

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import remove_min [as 别名]
class Djikstraks(object):

    """
    Goal is to find single source shortest path
    to all the other vertices

    Its exactly same as prims algorithm. The only difference is
    when we calculate the distance to a vertex, its the some of
    the distance of min vertex to the neighbour and source vertex
    to min vertex

    """

    class Node(object):
        def __init__(self, data, label):
            self.data = data
            self.label = label

    def __init__(self):
        self.pq = PriorityQueue()
        self.discovered = {}
        self.distance = {}
        self.res = []

    def build_priority_queue(self, graph):
        """
        Build the priority queue by adding inf to all the vertices
        and update the location of each vertex in the heap
        accordingly
        """
        index = 0
        for vertices in graph:
            self.pq.myHeap.append(self.Node(float('inf'), vertices))
            self.pq.location[vertices] = index
            index += 1

    def djikstras(self, graph):
        """
        Remove the minimum weight vertex from the heap and check its
        neighbours. If the weight from the minimum vertex to its
        neighbour is less than that of the neighbours, update the
        neighbours weight.

        Also, update the discovered dict, saying you reached the neighbour
        from this vertex

        Update the distance also, he distance is the sum of the distance
        from source to min node and the distance from min node to the neighbour
        """
        if self.pq.myHeap:

            min_node = self.pq.remove_min()

            for neighbour, weight in graph[min_node.label].items():
                # I need to check if neighbour exists in location dict
                # because I am constantly deleting and updating the
                # location. I use location and not heap because heap
                # stores obj's

                # This also ensures that I don't check the neighbour if
                # it was already deleted from the queue (in other words; if
                # the edge already made it to result)
                if neighbour in self.pq.location:
                    if weight < self.pq.myHeap[self.pq.location[neighbour]].data:
                        self.pq.update(neighbour, weight)
                        self.discovered[neighbour] = min_node.label
                        self.distance[neighbour] = self.distance[min_node.label] + weight

            self.djikstras(graph)

    def main(self, graph, start='A'):
        """
        Note: The data value of the start vertex should be 0, as this
        will make sure we remove the start vertex first (since every other
        vertex is inf)

        The distance of the start vertex is set to 0 as well
        """
        self.build_priority_queue(graph)
        self.pq.myHeap[self.pq.location[start]].data = 0
        self.discovered[start] = None
        self.distance[start] = 0
        self.djikstras(graph)
        print self.discovered
        print self.distance
开发者ID:mmadhavan,项目名称:CtCI-6th-Edition,代码行数:87,代码来源:djikstras.py

示例2: PrimsMinimumSpaningTree

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import remove_min [as 别名]
class PrimsMinimumSpaningTree(object):

    """
    Goal is to find the minimum spanning tree of
    a weighted undirected graph

    Algorithm is pretty straightforward, for every vertex
    check which of it neighbours has the least weighted
    edge, pick that edge (it will be part of the minimum
    spanning tree) and move to that vertex and repeat the
    same


    Some optimizations:

    When we explore the neighbours of
    a vertex, we need to record the weights to determine
    which edge has the least weight. Hence a priority queue
    makes sense here, we can have the vertices as keys and
    weights as values, this will also help in extracting/remove
    min in constant time.

    After we remove min, we need a record of which edge goes in
    the final spanning tree, for this we use a discovered map.
    This map is updated at the same time we record the weights
    of the neighbours in the priority queue. So, when we do a
    extract/remove min we look at the discovered map to find out
    which edge was responsible for this min value and add it to
    the final result

    The last optimization is to make sure when the vertex is
    looking at all its neighbours (to calculate weight) it
    doesn't consider the edges that are already part of the
    spanning tree, for this we need to modify the priority queue
    so that it supports a contains operation. This can be
    achieved by internally having a map in the priority queue
    that stores the location (index) of the vertices in the queue.
    We can now refer to this map to find if the vertex exists in
    the queue and if does consider that vertex (because when we do
    extract min, we remove the min vertex and that becomes part of
    the spanning tree - we don't want to look at this vertex again)

    Also note, the internal map can also be an internal array if we
    just want to find out if a given vertex exists in the queue or not.
    However, having a map will also help us in update operations of
    vertices (remember we keep updating the value of the vertices
    in the queue)
    """

    class Node(object):
        def __init__(self, data, label):
            self.data = data
            self.label = label

    def __init__(self):
        self.pq = PriorityQueue()
        self.discovered = {}
        self.res = []

    def build_priority_queue(self, graph):
        """
        Build the priority queue by adding inf to all the vertices
        and update the location of each vertex in the heap
        accordingly
        """
        index = 0
        for vertices in graph:
            self.pq.myHeap.append(self.Node(float('inf'), vertices))
            self.pq.location[vertices] = index
            index += 1

    def prim(self, graph):
        """
        Remove the minimum weight vertex from the heap and check its
        neighbours. If the weight from the minimum vertex to its
        neighbour is less than that of the neighbours, update the
        neighbours weight.

        Also, update the discovered dict, saying you reached the neighbour
        from this vertex
        """
        if self.pq.myHeap:

            min_node = self.pq.remove_min()

            for neighbour, weight in graph[min_node.label].items():
                # I need to check if neighbour exists in location dict
                # because I am constantly deleting and updating the
                # location. I use location and not heap because heap
                # stores obj's

                # This also ensures that I don't check the neighbour if
                # it was already deleted from the queue (in other words; if
                # the edge already made it to result)
                if neighbour in self.pq.location:
                    if weight < self.pq.myHeap[self.pq.location[neighbour]].data:
                        self.pq.update(neighbour, weight)
                        self.discovered[neighbour] = min_node.label

            edge = '{0} -> {1}'.format(self.discovered[min_node.label],
#.........这里部分代码省略.........
开发者ID:mmadhavan,项目名称:CtCI-6th-Edition,代码行数:103,代码来源:prims.py


注:本文中的priorityQueue.PriorityQueue.remove_min方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。