def djisktra(self, a, b): distances = [float("inf") for _ in self.vertices] distances[a] = 0 predecessors = [None for _ in self.vertices] # queue = PriorityQueue() queue = PriorityQueue() queue.enqueue((distances[a], self.vertices[a].label)) while True: if queue.empty(): break # print(queue) _, current = queue.dequeue() if current is b: break # dequeue a node we already looked at # this may not be necessary because it will just not decrease any travel times anyway else: # traverse adj list, and see if any are shorter than current dist for v in self.vertices[current].adj: temp = distances[current] + weight(self.vertices[current], self.vertices[v]) if distances[v] > temp: distances[v] = temp predecessors[v] = current queue.enqueue((temp, v)) # shouldn't this be (distances[v], v) count = 0 for distance in distances: if (distance != float("inf")): count+=1 #print((distances[b], predecessors[b], count)) return (distances, predecessors, count)
def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ dict_num = dict() for num in nums: if num not in dict_num: dict_num[num] = 1 else: dict_num[num] += 1 pq = PriorityQueue() for key in dict_num.keys(): if pq.getSize() < k: pq.enqueue(self.__Freq(key, dict_num[key])) continue if pq.getFront().freq < dict_num[key]: pq.dequeue() pq.enqueue(self.__Freq(key, dict_num[key])) re = [] while pq.isEmpty() is not True: re.insert(0, pq.dequeue().value) return re
class TestPriorityQueue(unittest.TestCase): def setUp(self): self.pq = PriorityQueue() def tearDown(self): self.pq = None def test_basic(self): self.assertTrue(self.pq.isEmpty()) self.assertEqual(0, len(self.pq)) def test_fill(self): """Fill up the queue.""" data = knuth_shuffle(range(1, 10)) for d in data: self.pq.enqueue(d) sorted_data = sorted(data) self.assertEqual(sorted_data[0], self.pq.peekFront()) self.assertEqual(sorted_data[len(sorted_data) - 1], self.pq.peekRear()) self.assertEqual(len(data), len(self.pq)) for d in sorted_data: self.assertEqual(d, self.pq.dequeue()) self.assertTrue(self.pq.isEmpty())
def buildTree(self, text): queue = PriorityQueue(cmp=lambda a,b: a.frequency > b.frequency) for v,f in dict(Counter(list(text))).items(): queue.enqueue(BinaryNode(v, f)) while queue.size() > 1: nodeL = queue.dequeue() nodeR = queue.dequeue() parent = BinaryNode(None, nodeL.frequency+nodeR.frequency) parent.left = nodeL parent.right = nodeR queue.enqueue(parent) self.root = queue.dequeue()
def test_enqueue(self): priority_queue = PriorityQueue() priority_queue.enqueue(10, 6) priority_queue.enqueue(20, 5) priority_queue.enqueue(30, 4) priority_queue.enqueue(40, 3) priority_queue.enqueue(50, 2) priority_queue.enqueue(60, 1) priority_queue.enqueue(70, 0) self.assertEqual([{0: 70}, {3: 40}, {1: 60}, {6: 10}, {4: 30}, {5: 20}, {2: 50}], priority_queue.returnQueue())
def test_dequeue(self): priority_queue = PriorityQueue() priority_queue.enqueue(10, 6) priority_queue.enqueue(20, 5) priority_queue.enqueue(30, 4) priority_queue.enqueue(40, 3) priority_queue.enqueue(50, 2) priority_queue.enqueue(60, 1) priority_queue.enqueue(70, 0) returned_node = priority_queue.dequeue() self.assertEqual(70, returned_node.get_value()) self.assertEqual([{1: 60}, {3: 40}, {2: 50}, {6: 10}, {4: 30}, {5: 20}], priority_queue.returnQueue())
def prim(g, source): # File de priorité priorityQ = PriorityQueue() # Garde trace des parents pour chaque noeud ancestors = {} # Arbre de poids minimum A = MST(g) # Initialisation pour tous les noeuds for node in g.get_nodes(): # côut inital = +∞ # coût source = 0 cost = sys.maxsize if node == source: cost = 0 # parent initial = None ancestors[node] = None # On pousse dans la file de priorité priorityQ.enqueue(node, cost) # Tant que la file n'est pas vide (ie. il reste des sommets à joindre) while len(priorityQ) != 0: # On récupère celui avec la priorité la plus faible curr = priorityQ.dequeue() # On récupère la liste de ses voisins qui restent encore à connecter (ie. qui sont encore dans la file) for neighboor in [value for value in priorityQ.get_list_items() if (curr, value) in g.get_adj_matrix()]: # Si le coût de ce noeud est plus élevé que le coût de l'arc if(priorityQ.get_priority(neighboor) > g.get_adj_matrix()[(curr, neighboor)].get_weight()): # On change le coût dans la file de ce noeud priorityQ.change_priority(neighboor, g.get_adj_matrix()[(curr, neighboor)].get_weight()) # Curr devient le nouveau parent de neighboor ancestors[neighboor] = curr # Lorsqu'on a la liste de tous les parents, on crée le graphe à partir de g for node in g.get_nodes(): # Seul le noeud source n'a pas de parent if node == source: continue A.add_edge(g.get_adj_matrix()[(node, ancestors[node])]) return A
from priorityQueue import PriorityQueue ER = PriorityQueue() ER.enqueue("common cold", 5) ER.enqueue("gunshot wound", 1) ER.enqueue("high fever", 4) ER.enqueue("broken arm", 2) ER.enqueue("flu", 3) print(ER.dequeue()) print(ER.dequeue()) print(ER.dequeue()) print(ER.dequeue()) print(ER.dequeue())