Last active
September 14, 2015 07:36
-
-
Save tawateer/67d730b1dfc50c6f92e6 to your computer and use it in GitHub Desktop.
堆排序例子
This file contains hidden or 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
import heapq | |
import random | |
class BtmkHeap(object): | |
def __init__(self, k): | |
self.k = k | |
self.data = [] | |
def Push(self, elem): | |
# Reverse elem to convert to max-heap | |
elem = -elem | |
# Using heap algorighem | |
if len(self.data) < self.k: | |
heapq.heappush(self.data, elem) | |
else: | |
topk_small = self.data[0] | |
if elem > topk_small: | |
heapq.heapreplace(self.data, elem) | |
def BtmK(self): | |
return sorted([-x for x in self.data]) | |
if __name__ == "__main__": | |
print "Hello" | |
list_rand = random.sample(xrange(1000000), 100) | |
th = BtmkHeap(3) | |
for i in list_rand: | |
th.Push(i) | |
print th.BtmK() | |
print sorted(list_rand)[0:3] |
This file contains hidden or 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
import heapq | |
import random | |
class TopkHeap(object): | |
def __init__(self, k): | |
self.k = k | |
self.data = [] | |
def Push(self, elem): | |
if len(self.data) < self.k: | |
heapq.heappush(self.data, elem) | |
else: | |
topk_small = self.data[0] | |
if elem > topk_small: | |
heapq.heapreplace(self.data, elem) | |
def TopK(self): | |
return [x for x in reversed([heapq.heappop(self.data) for x in xrange(len(self.data))])] | |
if __name__ == "__main__": | |
print "Hello" | |
list_rand = random.sample(xrange(1000000), 100) | |
th = TopkHeap(3) | |
for i in list_rand: | |
th.Push(i) | |
print th.TopK() | |
print sorted(list_rand, reverse=True)[0:3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment