Skip to content

Instantly share code, notes, and snippets.

@athulmurali
Last active June 18, 2019 02:57
Show Gist options
  • Save athulmurali/82c71fee06e90ee3c08a1d89c698c46f to your computer and use it in GitHub Desktop.
Save athulmurali/82c71fee06e90ee3c08a1d89c698c46f to your computer and use it in GitHub Desktop.
K largest and smallest elements in python
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))
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