Created
April 10, 2015 14:07
-
-
Save Averroes/d795fb60718b516f2f3c to your computer and use it in GitHub Desktop.
finding the largest or smallest n items
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
# example.py | |
# | |
# Example of using heapq to find the N smallest or largest items | |
import heapq | |
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']) | |
print(cheap) | |
print(expensive) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment