Skip to content

Commit c7c7ce7

Browse files
author
Yuting Liu
committed
Add max heap version of heappush
1 parent cb944d0 commit c7c7ce7

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

Lib/heapq.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,11 @@ def _heappop_max(heap):
188188
return returnitem
189189
return lastelt
190190

191+
def heappush_pop(heap, item):
192+
"""Maxheap version of a heappush."""
193+
heap.append(item)
194+
_siftdown_max(heap, 0, len(heap)-1)
195+
191196
def _heapreplace_max(heap, item):
192197
"""Maxheap version of a heappop followed by a heappush."""
193198
returnitem = heap[0] # raises appropriate IndexError if heap is empty

Lib/test/test_heapq.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# _heapq.nlargest/nsmallest are saved in heapq._nlargest/_smallest when
1515
# _heapq is imported, so check them there
1616
func_names = ['heapify', 'heappop', 'heappush', 'heappushpop', 'heapreplace',
17-
'_heappop_max', '_heapreplace_max', '_heapify_max']
17+
'_heappop_max', '_heappush_max', '_heapreplace_max', '_heapify_max']
1818

1919
class TestModules(TestCase):
2020
def test_py_functions(self):
@@ -160,6 +160,13 @@ def test_heappop_max(self):
160160
self.assertEqual(self.module._heappop_max(h), 3)
161161
self.assertEqual(self.module._heappop_max(h), 2)
162162

163+
def test_heappush_max(self):
164+
h = [3, 2]
165+
self.module._heappush_max(h, 3)
166+
self.assertEqual(h[0], 3)
167+
self.module._heappush_max(h, 5)
168+
self.assertEqual(h[0], 5)
169+
163170
def test_heapsort(self):
164171
# Exercise everything with repeated heapsort checks
165172
for trial in range(100):

0 commit comments

Comments
 (0)