Last active
December 19, 2022 16:16
-
-
Save fgshun/c2843723597f225580226135a23a1f76 to your computer and use it in GitHub Desktop.
Python heapq で最大ヒープ (max heap)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from heapq import heapify, heappop, heappush, heappushpop, heapreplace | |
from operator import neg | |
class MaxHeap: | |
def __init__(self, iterator): | |
self.seq = list(map(neg, iterator)) | |
heapify(self.seq) | |
def push(self, v): | |
heappush(self.seq, -v) | |
def pop(self): | |
return -heappop(self.seq) | |
def pushpop(self, v): | |
return -heappushpop(self.seq, -v) | |
def replace(self, v): | |
return -heapreplace(self.seq, -v) | |
def __len__(self): | |
return len(self.seq) | |
def __getitem__(self, index): | |
return -self.seq[index] | |
def __iter__(self): | |
return map(neg, self.seq) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment