Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-110067: Make max heap methods public and add missing ones#130725

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
encukou merged 27 commits intopython:mainfromStanFromIreland:add-heapq-max
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from18 commits
Commits
Show all changes
27 commits
Select commitHold shift + click to select a range
eccf484
Initial addition
StanFromIrelandMar 1, 2025
beaf915
Add C imp
StanFromIrelandMar 1, 2025
c143ae2
Benedikts suggestions
StanFromIrelandMar 1, 2025
167525d
Benedikts suggestions
StanFromIrelandMar 1, 2025
1b0b6f3
Update Modules/_heapqmodule.c with Benedikts suggestion
StanFromIrelandMar 1, 2025
fc46707
Fix mistake (extra underscores)
StanFromIrelandMar 1, 2025
f4fd94a
Benedikt's requested changes
StanFromIrelandMar 1, 2025
cebbc88
Missed one of Benedikt's requested changes
StanFromIrelandMar 1, 2025
3cde6c6
Benedikts suggestion
StanFromIrelandMar 1, 2025
5d2d387
Benedikts Suggestions
StanFromIrelandMar 2, 2025
a499cd4
Fix doc warnings
StanFromIrelandMar 2, 2025
abe0a95
Improve entries
StanFromIrelandMar 2, 2025
3561206
Address some of Petr's suggestions
StanFromIrelandMar 10, 2025
8fd1a03
Clean up and add missing
StanFromIrelandMar 10, 2025
8ab97c2
Update Doc/library/heapq.rst
StanFromIrelandMar 17, 2025
623cae7
Merge branch 'main' into add-heapq-max
StanFromIrelandApr 25, 2025
81db251
Sort and add missing C implementation
StanFromIrelandMay 2, 2025
38cbf13
Petr's list suggestion
StanFromIrelandMay 2, 2025
b6f4db4
heappushpop_max fixup
StanFromIrelandMay 2, 2025
61c9285
Improve test
StanFromIrelandMay 4, 2025
ebe00dc
Switch to <
StanFromIrelandMay 5, 2025
bc0dd66
Clean up test
StanFromIrelandMay 5, 2025
988b2d3
Reword the docs
encukouMay 5, 2025
6efd70c
Add max-heap variants for the other tests
encukouMay 5, 2025
4ba533b
Apply suggestions from code review
encukouMay 5, 2025
160bc35
Merge pull request #1 from encukou/add-heapq-max
StanFromIrelandMay 5, 2025
742c46c
final touchups
StanFromIrelandMay 5, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletionsDoc/library/heapq.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,8 +16,10 @@
This module provides an implementation of the heap queue algorithm, also known
as the priority queue algorithm.

Heaps are binary trees for which every parent node has a value less than or
equal to any of its children. We refer to this condition as the heap invariant.
Min-heaps (resp. max-heaps) are binary trees for which every parent node
has a value less than (resp. greater than) or equal to any of its children.
We refer to this condition as the heap invariant. Unless stated otherwise,
*heaps* refer to min-heaps.

This implementation uses arrays for which
``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting
Expand DownExpand Up@@ -82,6 +84,52 @@ The following functions are provided:
on the heap.


For max-heaps, the following functions are provided:


.. function:: heapify_max(x)

Transform list *x* into a max-heap, in-place, in linear time.

.. versionadded:: next


.. function:: heappush_max(heap, item)

Push the value *item* onto the max-heap *heap*, maintaining the heap invariant.

.. versionadded:: next


.. function:: heappop_max(heap)

Pop and return the largest item from the max-heap *heap*, maintaining the heap
invariant. If the max-heap is empty, :exc:`IndexError` is raised. To access the
largest item without popping it, use ``heap[0]``.

.. versionadded:: next


.. function:: heappushpop_max(heap, item)

Push *item* on the max-heap *heap*, then pop and return the largest item from *heap*.
The combined action runs more efficiently than :func:`heappush_max`
followed by a separate call to :func:`heappop_max`.

.. versionadded:: next


.. function:: heapreplace_max(heap, item)

Pop and return the largest item from the max-heap *heap* and also push the new *item*.
The max-heap size doesn't change. If the max-heap is empty, :exc:`IndexError` is raised.

The value returned may be smaller than the *item* added. Refer to the analogous
function :func:`heapreplace` for detailed usage notes.

.. versionadded:: next


The module also offers three general purpose functions based on heaps.


Expand Down
12 changes: 12 additions & 0 deletionsDoc/whatsnew/3.14.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -844,6 +844,18 @@ graphlib
(Contributed by Daniel Pope in :gh:`130914`)


heapq
-----

* Add functions for working with max-heaps:

* :func:`heapq.heapify_max`,
* :func:`heapq.heappush_max`,
* :func:`heapq.heappop_max`,
* :func:`heapq.heapreplace_max`
* :func:`heapq.heappushpop_max`


hmac
----

Expand Down
51 changes: 29 additions & 22 deletionsLib/heapq.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -178,7 +178,7 @@ def heapify(x):
for i in reversed(range(n//2)):
_siftup(x, i)

def_heappop_max(heap):
defheappop_max(heap):
"""Maxheap version of a heappop."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
Expand All@@ -188,19 +188,32 @@ def _heappop_max(heap):
return returnitem
return lastelt

def_heapreplace_max(heap, item):
defheapreplace_max(heap, item):
"""Maxheap version of a heappop followed by a heappush."""
returnitem = heap[0] # raises appropriate IndexError if heap is empty
heap[0] = item
_siftup_max(heap, 0)
return returnitem

def _heapify_max(x):
def heappush_max(heap, item):
"""Maxheap version of a heappush."""
heap.append(item)
_siftdown_max(heap, 0, len(heap)-1)

def heappushpop_max(heap, item):
"""Maxheap fast version of a heappush followed by a heappop."""
if heap and heap[0] < item:
item, heap[0] = heap[0], item
_siftup_max(heap, 0)
return item

def heapify_max(x):
"""Transform list into a maxheap, in-place, in O(len(x)) time."""
n = len(x)
for i in reversed(range(n//2)):
_siftup_max(x, i)


# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
# is the index of a leaf with a possibly out-of-order value. Restore the
# heap invariant.
Expand DownExpand Up@@ -335,9 +348,9 @@ def merge(*iterables, key=None, reverse=False):
h_append = h.append

if reverse:
_heapify =_heapify_max
_heappop =_heappop_max
_heapreplace =_heapreplace_max
_heapify =heapify_max
_heappop =heappop_max
_heapreplace =heapreplace_max
direction = -1
else:
_heapify = heapify
Expand DownExpand Up@@ -490,10 +503,10 @@ def nsmallest(n, iterable, key=None):
result = [(elem, i) for i, elem in zip(range(n), it)]
if not result:
return result
_heapify_max(result)
heapify_max(result)
top = result[0][0]
order = n
_heapreplace =_heapreplace_max
_heapreplace =heapreplace_max
for elem in it:
if elem < top:
_heapreplace(result, (elem, order))
Expand All@@ -507,10 +520,10 @@ def nsmallest(n, iterable, key=None):
result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
if not result:
return result
_heapify_max(result)
heapify_max(result)
top = result[0][0]
order = n
_heapreplace =_heapreplace_max
_heapreplace =heapreplace_max
for elem in it:
k = key(elem)
if k < top:
Expand DownExpand Up@@ -583,19 +596,13 @@ def nlargest(n, iterable, key=None):
from _heapq import *
except ImportError:
pass
try:
from _heapq import _heapreplace_max
except ImportError:
pass
try:
from _heapq import _heapify_max
except ImportError:
pass
try:
from _heapq import _heappop_max
except ImportError:
pass

# For backwards compatibility
_heappop_max = heappop_max
_heapreplace_max = heapreplace_max
_heappush_max = heappush_max
_heappushpop_max = heappushpop_max
_heapify_max = heapify_max

if __name__ == "__main__":

Expand Down
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp