Last active
June 18, 2019 02:57
-
-
Save athulmurali/82c71fee06e90ee3c08a1d89c698c46f to your computer and use it in GitHub Desktop.
K largest and smallest elements in python
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
import heapq | |
def k_largest(arr,k): | |
h= [] | |
heapq.heapify(h) | |
for i in arr: | |
heapq.heappush(h,i) | |
if len(h) > k : | |
heapq.heappop(h) | |
result = [] | |
while h: | |
result.insert(0,heapq.heappop(h)) | |
return result | |
if __name__=="k_largest": | |
print(k_largest([5,6,7,1,2,3,4,100,200,400,1234,0,0,12,123,100000], 3)) |
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
def k_smallest(arr,k): | |
h= [] | |
heapq.heapify(h) | |
for i in arr: | |
heapq.heappush(h,-i) | |
if len(h) > k : | |
-heapq.heappop(h) | |
result = [] | |
while h: | |
result.append(heapq.heappop(h)) | |
return result | |
if __name__=="k_smallest": | |
print(k_smallest([5,6,7,1,2,3,4,100,200,400,1234,0,0,12,123,100000], 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment