Python heapq.heapify() Examples
The following are 30
code examples of heapq.heapify().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
heapq
, or try the search function
.
Example #1
Source File: manager.py From Paradrop with Apache License 2.0 | 6 votes |
def unload(self, execute=True): commands = CommandList() undoWork = ConfigObject.prioritizeConfigs(self.currentConfig.values()) heapq.heapify(undoWork) while undoWork: prio, config = heapq.heappop(undoWork) commands.extend(config.revert(self.currentConfig)) # Finally, execute the commands. if execute and self.execCommands: self.execute(commands) self.previousCommands = commands self.currentConfig = dict() return True
Example #2
Source File: 1086-前五科的均分.py From LeetCode-Python with GNU General Public License v3.0 | 6 votes |
def highFive(self, items): """ :type items: List[List[int]] :rtype: List[List[int]] """ record = dict() for item in items: sd, sc = item[0], item[1] if sd not in record: record[sd] = [sc] heapq.heapify(record[sd]) else: heapq.heappush(record[sd], sc) if len(record[sd]) > 5: heapq.heappop(record[sd]) print record[sd] res = [] for key, val in record.items(): res.append([key, sum(val) // 5]) # print record return res
Example #3
Source File: Delete Digits.py From LintCode with Apache License 2.0 | 6 votes |
def DeleteDigits_error(self, A, k): """ Remove and keep the n-k largest numbers heap: O(n lg (n-k)) error in case: 254193, 1 :param A: A positive integer which has N digits, A is a string. :param k: Remove k digits. :return: A string """ lst = map(int, list(str(A))) m = len(lst)-k tuples = [(-lst[i], i) for i in xrange(m)] # negative sign for max heap heapq.heapify(tuples) for i in xrange(m, len(lst)): if -tuples[0][0] > lst[i]: heapq.heappop(tuples) heapq.heappush(tuples, (-lst[i], i)) rets = [elt[1] for elt in tuples] rets.sort() rets = map(lambda x: str(lst[x]), rets) return "".join(rets)
Example #4
Source File: isotp.py From scapy with GNU General Public License v2.0 | 6 votes |
def cancel(handle): """Provided its handle, cancels the execution of a timeout.""" handles = TimeoutScheduler._handles with TimeoutScheduler._mutex: if handle in handles: # Time complexity is O(n) handle._cb = None handles.remove(handle) heapq.heapify(handles) if len(handles) == 0: # set the event to stop the wait - this kills the thread TimeoutScheduler._event.set() else: raise Scapy_Exception("Handle not found")
Example #5
Source File: IterMap.py From sequitur-g2p with GNU General Public License v2.0 | 6 votes |
def mergeSort(seqs): """ perform merge sort on a list of sorted iterators """ queue = [] for s in seqs: s = assertIsSorted(s) it = iter(s) try: queue.append((it.next(), it.next)) except StopIteration: pass heapq.heapify(queue) while queue: item, it = queue[0] yield item try: heapq.heapreplace(queue, (it(), it)) except StopIteration: heapq.heappop(queue) # ---------------------------------------------------------------------------
Example #6
Source File: probe.py From plugins with BSD 3-Clause "New" or "Revised" License | 6 votes |
def schedule(plugin): # List of scheduled calls with next runtime, function and interval next_runs = [ (time() + 300, clear_temporary_exclusion, 300), (time() + plugin.probe_interval, start_probe, plugin.probe_interval), (time() + 1, poll_payments, 1), ] heapq.heapify(next_runs) while True: n = heapq.heappop(next_runs) t = n[0] - time() if t > 0: sleep(t) # Call the function n[1](plugin) # Schedule the next run heapq.heappush(next_runs, (time() + n[2], n[1], n[2]))
Example #7
Source File: merge_k_Sorted_lists.py From Competitive_Programming with MIT License | 6 votes |
def merge(lists): merged_list = [] heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] heapq.heapify(heap) while heap: #print(heap) val, list_ind, element_ind = heapq.heappop(heap) merged_list.append(val) if element_ind + 1 < len(lists[list_ind]): next_tuple = (lists[list_ind][element_ind + 1], list_ind, element_ind + 1) heapq.heappush(heap, next_tuple) return merged_list #Test Cases
Example #8
Source File: Solution.py From leetcode-solutions with MIT License | 6 votes |
def mergeKLists(self, lists: List[ListNode]) -> ListNode: hp = [] nodes = list(lists) for idx in range(len(nodes)): node = nodes[idx] if node is not None: hp.append((node.val, idx)) heapq.heapify(hp) head = None prev = None while hp: val, idx = heapq.heappop(hp) node = nodes[idx] if head is None: head = node if prev is not None: prev.next = node ne = node.next if ne is not None: heapq.heappush(hp, (ne.val, idx)) nodes[idx] = ne prev = node return head
Example #9
Source File: ical.py From ccs-calendarserver with Apache License 2.0 | 6 votes |
def merge(*iterables): """ Merge sorted iterables into one sorted iterable. @param iterables: arguments are iterables which yield items in sorted order. @return: an iterable of all items generated by every iterable in C{iterables} in sorted order. """ heap = [] for iterable in iterables: iterator = iter(iterable) for value in iterator: heap.append((value, iterator)) break heapq.heapify(heap) while heap: value, iterator = heap[0] yield value for value in iterator: heapq.heapreplace(heap, (value, iterator)) break else: heapq.heappop(heap)
Example #10
Source File: nlp.py From numpy-ml with GNU General Public License v3.0 | 5 votes |
def _build_tree(self, text): """Construct Huffman Tree""" PQ = [] if isinstance(text, Vocabulary): counts = text.counts else: counts = self._counter(text) for (k, c) in counts.items(): PQ.append(Node(k, c)) # create a priority queue with priority = item frequency heapq.heapify(PQ) while len(PQ) > 1: node1 = heapq.heappop(PQ) # item with smallest frequency node2 = heapq.heappop(PQ) # item with second smallest frequency parent = Node(None, node1.val + node2.val) parent.left = node1 parent.right = node2 heapq.heappush(PQ, parent) self._root = heapq.heappop(PQ)
Example #11
Source File: 5.py From algorithm_course with GNU General Public License v3.0 | 5 votes |
def create_huffman_tree(txt): q = [TreeNode(c, cnt) for c, cnt in collections.Counter(txt).items()] heapq.heapify(q) while len(q) > 1: a, b = heapq.heappop(q), heapq.heappop(q) heapq.heappush(q, TreeNode('', a.cnt + b.cnt, a, b)) return q.pop()
Example #12
Source File: rrule.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def __next__(self): try: self.dt = advance_iterator(self.gen) except StopIteration: if self.genlist[0] is self: heapq.heappop(self.genlist) else: self.genlist.remove(self) heapq.heapify(self.genlist)
Example #13
Source File: rrule.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def _iter(self): rlist = [] self._rdate.sort() self._genitem(rlist, iter(self._rdate)) for gen in [iter(x) for x in self._rrule]: self._genitem(rlist, gen) exlist = [] self._exdate.sort() self._genitem(exlist, iter(self._exdate)) for gen in [iter(x) for x in self._exrule]: self._genitem(exlist, gen) lastdt = None total = 0 heapq.heapify(rlist) heapq.heapify(exlist) while rlist: ritem = rlist[0] if not lastdt or lastdt != ritem.dt: while exlist and exlist[0] < ritem: exitem = exlist[0] advance_iterator(exitem) if exlist and exlist[0] is exitem: heapq.heapreplace(exlist, exitem) if not exlist or ritem != exlist[0]: total += 1 yield ritem.dt lastdt = ritem.dt advance_iterator(ritem) if rlist and rlist[0] is ritem: heapq.heapreplace(rlist, ritem) self._len = total
Example #14
Source File: ftpserver.py From script-languages with MIT License | 5 votes |
def __call__(self): now = time.time() calls = [] while self._tasks: if now < self._tasks[0].timeout: break call = heapq.heappop(self._tasks) if not call.cancelled: calls.append(call) else: self._cancellations -= 1 for call in calls: if call._repush: heapq.heappush(self._tasks, call) call._repush = False continue try: call.call() except (KeyboardInterrupt, SystemExit, asyncore.ExitNow): raise except: logerror(traceback.format_exc()) # remove cancelled tasks and re-heapify the queue if the # number of cancelled tasks is more than the half of the # entire queue if self._cancellations > 512 \ and self._cancellations > (len(self._tasks) >> 1): self._cancellations = 0 self._tasks = [x for x in self._tasks if not x.cancelled] self.reheapify()
Example #15
Source File: rrule.py From bash-lambda-layer with MIT License | 5 votes |
def _iter(self): rlist = [] self._rdate.sort() self._genitem(rlist, iter(self._rdate)) for gen in [iter(x) for x in self._rrule]: self._genitem(rlist, gen) exlist = [] self._exdate.sort() self._genitem(exlist, iter(self._exdate)) for gen in [iter(x) for x in self._exrule]: self._genitem(exlist, gen) lastdt = None total = 0 heapq.heapify(rlist) heapq.heapify(exlist) while rlist: ritem = rlist[0] if not lastdt or lastdt != ritem.dt: while exlist and exlist[0] < ritem: exitem = exlist[0] advance_iterator(exitem) if exlist and exlist[0] is exitem: heapq.heapreplace(exlist, exitem) if not exlist or ritem != exlist[0]: total += 1 yield ritem.dt lastdt = ritem.dt advance_iterator(ritem) if rlist and rlist[0] is ritem: heapq.heapreplace(rlist, ritem) self._len = total
Example #16
Source File: recipe-437116.py From code with MIT License | 5 votes |
def __init__(self, t=[]): self.extend(t) self.heapify()
Example #17
Source File: bgp.py From ipmininet with GNU General Public License v2.0 | 5 votes |
def _find_peer_address(base: 'Router', peer: str, v6=False) \ -> Tuple[Optional[str], Optional['Router']]: """Return the IP address that base should try to contact to establish a peering""" visited = set() # type: Set[IPIntf] to_visit = {i.name: i for i in realIntfList(base)} prio_queue = [(0, i) for i in to_visit.keys()] heapq.heapify(prio_queue) # Explore all interfaces in base ASN recursively, until we find one # connected to the peer while to_visit: path_cost, i = heapq.heappop(prio_queue) if i in visited: continue i = to_visit.pop(i) visited.add(i) for n in i.broadcast_domain.routers: if n.node.name == peer: if not v6: return n.ip, n.node if n.ip6 and not ip_address(n.ip6).is_link_local: return n.ip6, n.node return None, None if n.node.asn == base.asn or not n.node.asn: for i in realIntfList(n.node): to_visit[i.name] = i heapq.heappush(prio_queue, (path_cost + i.igp_metric, i.name)) return None, None
Example #18
Source File: rrule.py From bash-lambda-layer with MIT License | 5 votes |
def __next__(self): try: self.dt = advance_iterator(self.gen) except StopIteration: if self.genlist[0] is self: heapq.heappop(self.genlist) else: self.genlist.remove(self) heapq.heapify(self.genlist)
Example #19
Source File: sched.py From ironpython3 with Apache License 2.0 | 5 votes |
def cancel(self, event): """Remove an event from the queue. This must be presented the ID as returned by enter(). If the event is not in the queue, this raises ValueError. """ with self._lock: self._queue.remove(event) heapq.heapify(self._queue)
Example #20
Source File: Kth Prime Number.py From LintCode with Apache License 2.0 | 5 votes |
def kthPrimeNumber_error(self, k): """ heap and queue Erroneous on re-appending the next items on the same queue Example of errors: 45 is repeated, 45 = 3*3*5 and 45 = 3*5*3 :param k: :return: """ import heapq h1 = QueueNode(3) h2 = QueueNode(5) h3 = QueueNode(7) heap = [h1, h2, h3] heapq.heapify(heap) for cnt in xrange(k-1): h = heapq.heappop(heap) if h == h1: for i in [3, 5, 7]: h1.q.append(i*h1.val) h1.next() heapq.heappush(heap, h1) elif h == h2: for i in [5, 7]: h2.q.append(i*h2.val) h2.next() heapq.heappush(heap, h2) else: for i in [7]: h3.q.append(i*h3.val) h3.next() heapq.heappush(heap, h3) return heapq.heappop(heap).val
Example #21
Source File: Kth Prime Number.py From LintCode with Apache License 2.0 | 5 votes |
def kthPrimeNumber(self, k): """ heap and queue :param k: :return: """ import heapq h1 = QueueNode(3) h2 = QueueNode(5) h3 = QueueNode(7) heap = [h1, h2, h3] heapq.heapify(heap) for cnt in xrange(k-1): h = heapq.heappop(heap) if h == h1: h1.q.append(h1.val*3) h2.q.append(h1.val*5) h3.q.append(h1.val*7) elif h == h2: h2.q.append(h2.val*5) h3.q.append(h2.val*7) else: h3.q.append(h3.val*7) h.next() heapq.heappush(heap, h) return heapq.heappop(heap).val
Example #22
Source File: huffman_coding.py From algorithms with MIT License | 5 votes |
def _create_tree(signs_frequency: dict) -> Node: nodes = [Node(frequency=frequency, sign=char_int) for char_int, frequency in signs_frequency.items()] heapq.heapify(nodes) while len(nodes) > 1: left = heapq.heappop(nodes) right = heapq.heappop(nodes) new_node = Node(frequency=left.frequency + right.frequency, left=left, right=right) heapq.heappush(nodes, new_node) return nodes[0] # root
Example #23
Source File: demo_plotter.py From momi2 with GNU General Public License v3.0 | 5 votes |
def __init__(self, name, x, times, N): self.name = name self.x = x if not times: self.time_stack = [] else: self.time_stack = list(times) hq.heapify(self.time_stack) self.curr_N = N self.curr_g = 0.0 self.curr_t = 0.0 self.points = [] self.active = False self.next_is_leaf = False
Example #24
Source File: astar.py From pysnake with GNU General Public License v3.0 | 5 votes |
def solve(self): self.path = [] if self.node_array and self.start_node and self.end_node: closed_nodes = set() opened_nodes = [] heapq.heapify(opened_nodes) heapq.heappush(opened_nodes, (self.start_node.f, self.start_node)) # 若待探索堆队列不为空 while opened_nodes: # 从待探索堆队列中取f值最小的node f, node = heapq.heappop(opened_nodes) # 将当前node放入已探索集合, 避免重复探索 closed_nodes.add(node) # 找到终点则生成路径坐标列表 self.path (包含起点和终点) if node is self.end_node: self.path = [] while node is not self.start_node: self.path.append((node.x, node.y)) node = node.p self.path.append((self.start_node.x, self.start_node.y)) self.path.reverse() return # 结束函数并返回 # 找当前节点的邻居节点 adj_nodes = self.get_adjacent_nodes(node) for adj_node in adj_nodes: # 如果邻居节点为路, 且还未探索过 if adj_node.r and adj_node not in closed_nodes: # 如果邻居节点已在待探索列表中 if (adj_node.f, adj_node) in opened_nodes: # 如果当前节点已知成本优于邻居节点则更新邻居节点 if node.g < adj_node.g: self.update_node(adj_node, node) else: # 否则初始化邻居节点, 并将其放入待探索列表 self.update_node(adj_node, node) heapq.heappush(opened_nodes, (adj_node.f, adj_node))
Example #25
Source File: astar.py From coiltraine with MIT License | 5 votes |
def __init__(self): # open list self.opened = [] heapq.heapify(self.opened) # visited cells list self.closed = set() # grid cells self.cells = [] self.grid_height = None self.grid_width = None self.start = None self.end = None
Example #26
Source File: 1054-距离相等的条形码.py From LeetCode-Python with GNU General Public License v3.0 | 5 votes |
def rearrangeBarcodes(self, barcodes): """ :type barcodes: List[int] :rtype: List[int] """ from collections import Counter import heapq record = Counter(barcodes) #ͳ��ÿ�����ֳ��ֵ�Ƶ�� queue = [] for key, val in record.items(): queue.append([-val, key]) heapq.heapify(queue) #�������ȼ����� res = [] pre = None while queue or pre: if queue: cur = heapq.heappop(queue) #ȡ����ǰ���ִ�������Ԫ�أ����������ͬ���Ƚ��ȳ� #frequency, value = cur[0], cur[1] res.append(cur[1]) #�����ŵ����� cur[0] += 1 #������Ƶ�� - 1����ΪPython֧����С�ѣ�Ϊ�˴ﵽ���ѵ�Ч��������ȡ���෴������ if cur[0] == 0: #���Ԫ���Ѿ��ź��� cur = None else: cur = None if pre: #��ǰһ����������ٽ�����Ѳ��� heapq.heappush(queue, pre) pre = cur #����һ�ֵ�����pre������������ʱ��������ڶ�����Ա�������Ԫ�ز����ظ� return res
Example #27
Source File: prim.py From Python with MIT License | 5 votes |
def prim_heap(graph: list, root: Vertex) -> Iterator[tuple]: """Prim's Algorithm with min heap. Runtime: O((m + n)log n) with `m` edges and `n` vertices Yield: Edges of a Minimum Spanning Tree Usage: prim(graph, graph[0]) """ for u in graph: u.key = math.inf u.pi = None root.key = 0 h = [v for v in graph] hq.heapify(h) while h: u = hq.heappop(h) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): v.pi = u v.key = u.edges[v.id] hq.heapify(h) for i in range(1, len(graph)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1)
Example #28
Source File: curvemult.py From btclib with MIT License | 5 votes |
def _multi_mult( scalars: Sequence[int], JPoints: Sequence[JacPoint], ec: CurveGroup ) -> JacPoint: # source: https://cr.yp.to/badbatch/boscoster2.py if len(scalars) != len(JPoints): errMsg = "mismatch between number of scalars and points: " errMsg += f"{len(scalars)} vs {len(JPoints)}" raise ValueError(errMsg) # FIXME # check for negative scalars # x = list(zip([-n for n in scalars], JPoints)) x: List[Tuple[int, JacPoint]] = [] for n, PJ in zip(scalars, JPoints): if n == 0: continue x.append((-n, PJ)) if len(x) == 0: return INFJ heapq.heapify(x) while len(x) > 1: np1 = heapq.heappop(x) np2 = heapq.heappop(x) n1, p1 = -np1[0], np1[1] n2, p2 = -np2[0], np2[1] p2 = ec._add_jac(p1, p2) n1 -= n2 if n1 > 0: heapq.heappush(x, (-n1, p1)) heapq.heappush(x, (-n2, p2)) np1 = heapq.heappop(x) n1, p1 = -np1[0], np1[1] assert n1 < ec.n, "better to take the mod n" # n1 %= ec.n return _mult_jac(n1, p1, ec)
Example #29
Source File: main.py From uva-onlinejudge-solutions with MIT License | 5 votes |
def min_tree(points): """Use Prim's min spanning tree algorithm, to build min spannig tree""" # Initialize spanning tree vertices = [0,] # Spanning tree vertices edges = [] # Spanning tree edges # Initialize free vertices not in tree (distance, vertex, tree_vertex) free = [(99999999999, i+1, 0) for i, v in enumerate(points[1:])] def update_free(vertex): """Update distances from free vertices to tree after adding one of the free vertices to the tree""" coordv = points[vertex] for i, f in enumerate(free): dist, fvertex, _ = f coordf = points[fvertex] ndist = point_dist(coordf, coordv) if ndist < dist: free[i] = (ndist, fvertex, vertex) heapq.heapify(free) update_free(0) # Initialize for first vertex # Iterate through free vertex while free: dist, fvertex, vertex = heapq.heappop(free) vertices.append(fvertex) edges.append((vertex, fvertex)) update_free(fvertex) return vertices, edges
Example #30
Source File: ftpserver.py From script-languages with MIT License | 5 votes |
def reheapify(self): heapq.heapify(self._tasks)