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


Python PriorityQueue.isEmpty方法代码示例

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


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

示例1: singleSourceShortestPath

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n) # ensure that srcID is between 0 and size of graph.
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue
        
        for i in range(0,self.n): # Iterate through all vertex ID
            if  i == srcID:     # If ID is srcID
                pq.set(i, 0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity
        
        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        while not pq.isEmpty():  # loop until priority queue is empty.
            (node, dist) = pq.extractMin() # extract smallest dist node.
            d[node] = dist # update dictionary with shortest distance.
            for (vertex, weight) in self.adjList[node]: # check the adjacency list of popped node.
                newDist = dist + weight # calculate new distance.
                if pq.hasKey(vertex): # if we haven't already popped the node in the adjacency list yet.
                    if newDist < pq.get(vertex): # check distance vs new calculated dist.
                        pq.set(vertex, newDist) # update priority queue.
                        pi[vertex] = node # update parent list.

        return (d, pi)
开发者ID:christwt,项目名称:Algorithms,代码行数:35,代码来源:myGraph.py

示例2: prim

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
def prim(aGraph, startVertex):
    # create a priority queue that uses distance as the value to determine priority and thus its position
    # use the distance to the vertex as the priority because while exploring the next vertex, want to explore the vertex that has the smallest distance
    # decreaseKey method used when the distance to a vertex that is already in the queue is reduced, and thus moves that vertex toward the front of the queue.
    pQueue = PriorityQueue()
    # initialize the state of the graph 
    for vertex in aGraph:
        # initialally all vertices values are = infinity (sys.maxint) because we assume the greatest value and then update appropiately
        vertex.setDistance(sys.maxsize)
        vertex.setPred(None)
    
    # distance represents distance from the startVertex, trivially 0 for the startVertex
    startVertex.setDistance(0)
    # key value pair
    # key is distance and vertex is the value
    pQueue.buildHeap([ (vertex.getDistance(), vertex) for vertex in aGraph ])
    
    while not pQueue.isEmpty():
        currentVertex = pQueue.delMin()
        # iterate over the currentVertex's edges
        for nextVertex in currentVertex.getConnections():
            # calculate the weight from currentVertex to nextVertex
            newCost = currentVertex.getWeight(nextVertex)
            
            # found a shorter path
            # node is not considered to be part of the spanning tree until it is removed from the priority queue.
            # nextVertex in pQueue means that vertex is not yet in the spanning tree so it is safe to add (ensures an acyclic graph)
            if nextVertex in pQueue and newCost< nextVertex.getDistance():
                # assign the predecessor appropiately
                nextVertex.setPred(currentVertex)
                # set a new distance on the nextVertex
                nextVertex.setDistance(newCost)
                # update the priorityQueue with the correct values
                pQueue.decreaseKey(nextVertex, newCost)
开发者ID:AbhishekShah212,项目名称:Cuddling-with-a-Python-,代码行数:36,代码来源:minSpanTree.py

示例3: singleSourceShortestPath

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue

        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        d[srcID] = 0 # first node to dist map since while won't catch it.

        while not pq.isEmpty():
            min = pq.extractMin()
            # Look at neighbors
            for neighbor in self.adjList[min[0]]: # where neighbor has not yet been removed from pq?
                alt = min[1] + neighbor[1]
                if pq.hasKey(neighbor[0]) and alt < pq.get(neighbor[0]): # previously stored needs to be replayed
                    # Update distances and parents everywhere
                    pq.set(neighbor[0], alt)
                    d[neighbor[0]] = alt
                    pi[neighbor[0]] = min[0]
        return (d,pi)
开发者ID:Ditofry,项目名称:djikstras_example,代码行数:37,代码来源:myGraph.py

示例4: dijkstra

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
def dijkstra(aGraph, startVertex):
    # create a priority queue that uses distance as the value to determine priority and thus its position
    # use the distance to the vertex as the priority because while exploring the next vertex, want to explore the vertex that has the smallest distance
    # decreaseKey method used when the distance to a vertex that is already in the queue is reduced, and thus moves that vertex toward the front of the queue.
    pQueue = PriorityQueue()
    
    # distance represents distance from the startVertex, trivially 0 for the startVertex
    # initialally all vertices values are = infinity (sys.maxint) because we assume the greatest value and then update appropiately
    startVertex.setDistance(0)
    
    # key value pair
    # key is distance and vertex is the value
    pQueue.buildHeap([ (vertex.getDistance(), vertex) for vertex in aGraph ])
    
    while not pQueue.isEmpty():
        currentVertex = pQueue.delMin()
        # iterate over the currentVertex's edges
        for nextVertex in currentVertex.getConnections():
            # distance of current vertex and the weight of it's edges
            newDistance = currentVertex.getDistance() + currentVertex.getWeight(nextVertex)
            # found a shorter path
            if newDistance < nextVertex.getDistance():
                # set a new distance on the nextVertex
                nextVertex.setDistance(newDistance)
                # assign the predecessor appropiately
                nextVertex.setPred(currentVertex)
                # update the priorityQueue with the correct values
                pQueue.decreaseKey(nextVertex, newDistance)
开发者ID:AbhishekShah212,项目名称:Cuddling-with-a-Python-,代码行数:30,代码来源:dijkstraAlgorithm.py

示例5: Dijkstras

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
def Dijkstras(graph,start):   
	pq=PriorityQueue()
	start.setDistance(0)
	pq.buildHeap([(v.getDistance(),v) for v in graph])   # distance is the key in the priority queue
	while not pq.isEmpty():
		currentvertex=pq.delMin()
		for newvertex in currentvertex.getConnections():
			newDist=currentvertex.getDistance()+currentvertex.getWeight(newvertex)
			if newDist<newvertex.getDistance(): 
				# at the start the distance of all the vertices is set to maximum. That's why the if statement will be executed
				newvertex.setDistance(newDist)
				newvertex.setPredecessor(currentvertex)
				pq.decreaseKey(newvertex,newDist)
开发者ID:yashk2810,项目名称:Algorithms,代码行数:15,代码来源:dijkstras.py

示例6: singleSourceShortestPath

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)

        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue
        cur=self
        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity
        
        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        minKey, minDist=pq.extractMin()

        d[minKey]=minDist #set orignal source distance to 0
        pi[minKey]=minKey #set sources to orginal source



        while(pq.isEmpty()==False):# COMPLETE the Dijkstra code here

                lst=self.adjList[minKey]#grap array of lists of format (vertices,weight) for node minKey
                for n in lst:#loop through said list
                        
                        ##grap the next node attached to this node somehow
                        dist=n[1]+minDist#grab distance from list

                        node=n[0] #grab node from list
                        if(pq.hasKey(node)):#check if that nodes min dist has been found
                                if(pq.get(node)>dist):#check if path to the node from minKey is less then current path
                                        pq.set(node,dist)#set the nodes distance in the queue
                                        d[node]=dist#set the nodes distance in the return array
                                        pi[node]=minKey#sets the nodes parents

                minKey, minDist=pq.extractMin()#extract next node dont need to extract last node as all the paths will be filled would probably work better in a do while loop
                        

            
        return (d,pi)
开发者ID:BrandonSpitler,项目名称:algorithm,代码行数:52,代码来源:myGraph.py

示例7: prim

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
def prim(graph,start):     # it belongs to the family of greedy algorithms
	pq=PriorityQueue()
	for v in graph:
		v.setDistance(sys.maxsize)
		v.setPredecessor(None)
	start.setDistance(0)
	pq.buildHeap([(v.getDistance(),v) for v in graph])
	while not pq.isEmpty()
		currentvertex=pq.delMin()
		for newvertex in currentvertex.getConnections():
			newDist=currentvertex.getWeight(newvertex)
			if newDist<newvertex.getDistance() and newvertex in pq:
				newvertex.setDistance(newDist)
				newvertex.setPredecessor(currentvertex)
				pq.decreaseKey(newvertex,newDist)
开发者ID:yashk2810,项目名称:Algorithms,代码行数:17,代码来源:prims.py

示例8: singleSourceShortestPath

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue

        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity

        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices

        parent = None

        while not pq.isEmpty():
            minNode = pq.extractMin()
            if parent is None:
                d[minNode[0]] = minNode[1]
                pi[minNode[0]] = minNode[0]
            elif minNode[1] != pq.Inf:
                d[minNode[0]] = float(round(decimal.Decimal(minNode[1]), 2))
            else:
                d[minNode[0]] = pq.Inf

            lst = self.adjList[minNode[0]]
            for i in range(len(lst)):
                if pq.hasKey(lst[i][0]) and pq.get(lst[i][0]) > lst[i][1] + d[minNode[0]]:
                    pi[lst[i][0]] = minNode[0]
                    pq.set(lst[i][0], lst[i][1] + d[minNode[0]])

            parent = minNode[0]

        return (d,pi)
开发者ID:jacksonchen,项目名称:algorithms_hw,代码行数:45,代码来源:myGraph.py

示例9: Scheduler

# 需要导入模块: from priorityQueue import PriorityQueue [as 别名]
# 或者: from priorityQueue.PriorityQueue import isEmpty [as 别名]
class Scheduler():
    def __init__(self, aCpu):
        self.currentQueue = FifoQueue()
        self.cpu = aCpu

    def getNextPcb(self):
        return self.currentQueue.getMax()

    def addPcb(self, pcb):
        if(self.currentQueue.isEmpty() and not(self.cpu.havePcb())):
            pcb.toRunning()
            self.cpu.assignPcb(pcb)
        else:
            self.currentQueue.addPcb(pcb)

    def setFIFOMode(self):
        self.currentQueue = FifoQueue()

    def setPriorityMode(self):
        self.currentQueue = PriorityQueue(3,3)

    def removePid(self, aPid):
        self.currentQueue.removePid(aPid)
开发者ID:fernandodm,项目名称:sistemasoperativos,代码行数:25,代码来源:scheduler.py


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