Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

finding the largest or smallest N items in python

# Finding the largest or smallest N items using heapq
import heapq 

nums = [1, 8, 2, 23, 7, -4, 19, 23, 42, 38, 2]
print(heapq.nlargest(3, nums)) # 3 largest value 
print(heapq.nsmallest(3, nums)) # 3 smallest value 

portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #finding #largest #smallest #N #items #python
ADD COMMENT
Topic
Name
6+1 =