Skip to content

Instantly share code, notes, and snippets.

@aqd14
Last active September 15, 2019 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aqd14/322576873926d17b0af6db82e9d10571 to your computer and use it in GitHub Desktop.
Save aqd14/322576873926d17b0af6db82e9d10571 to your computer and use it in GitHub Desktop.
## Problem 1.1
### You have an N-element tuple or sequence that you would like to unpack into a collection of N variables.
```
p = (4, 5)
x, y = p # x = 4, y = 5
```
## Problem 1.2
#### You need to unpack N elements from an iterable, but the iterable may be longer than N elements, causing a “too many values to unpack” exception.
```
def drop_first_last(grades):
first, *middle, last = grades return avg(middle)
```
## Problem 1.3
### Keeping the last N items
```
from collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
# Example use on a file
if __name__ == '__main__':
with open('somefile.txt') as f:
for line, prevlines in search(f, 'python', 5):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-'*20)
```
## Problem 1.4
### Finding N largest/smallest items in a collections
```
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
```
Both functions also accept a key parameter that allows them to be used with more complicated data structures. For example:
```
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'])
```
## 1.8 Calculating with dictionary
### You want to perform various calculations (e.g., minimum value, maximum value, sort‐ ing, etc.) on a dictionary of data.
```
# Consider a dictionary that maps stock names to prices:
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
```
In order to perform useful calculations on the dictionary contents, it is often useful to invert the keys and values of the dictionary using `zip()`. For example, here is how to find the minimum and maximum price and stock name:
```
min_price = min(zip(prices.values(), prices.keys())) # min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys())) # max_price is (612.78, 'AAPL')
```
Similarly, to rank the data, use `zip()` with `sorted()`, as in the following:
```
prices_sorted = sorted(zip(prices.values(), prices.keys())) # prices_sorted is [(10.75, 'FB'), (37.2, 'HPQ'),
# (45.23, 'ACME'), (205.55, 'IBM'),
# (612.78, 'AAPL')]
```
When doing these calculations, be aware that `zip()` creates an iterator that can only be consumed once. For example, the following code is an error:
```
prices_and_names = zip(prices.values(), prices.keys())
print(min(prices_and_names)) # OK
print(max(prices_and_names)) # ValueError: max() arg is an empty sequence
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment