forked from dabeaz-course/python-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpcost.py
More file actions
26 lines (21 loc) · 750 Bytes
/
Copy pathpcost.py
File metadata and controls
26 lines (21 loc) · 750 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# pcost.py
import sys
def portfolio_cost(path):
stockdicts = []
with open(path) as f:
for row in f:
name, shares, price = row.split()
try:
shares = int(shares)
price = float(price)
d = dict(zip(['name', 'shares', 'price'], (name, shares, price)))
print(d)
stockdicts.append(d)
except ValueError as e:
print('Could not parse: ', row, end='')
print('Reason: ', e)
return sum(s['shares'] * s['price'] for s in stockdicts)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit('Usage: pcost portfile')
print('Total cost:', portfolio_cost(sys.argv[1]))