Visitar URL original
complete section 2 · dabeaz-course/practical-python@3a164fa · GitHub
Skip to content

Commit 3a164fa

Browse files
author
iram lee
committed
complete section 2
1 parent ffb2d20 commit 3a164fa

2 files changed

Lines changed: 18 additions & 14 deletions

File tree

‎Work/pcost.py‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,34 @@
22
#
33
# Exercise 1.27
44
import sys
5+
import csv
56

67
def portfolio_cost(filename):
7-
cost = 0.0
8+
total_cost = 0.0
89
stock_price = 0.0
910
num_of_shares = 0
1011
f = open(filename, 'rt')
11-
headers = next(f)
12+
lines = csv.reader(f)
13+
headers = next(lines)
1214

13-
for line in f:
15+
for lineno, line in enumerate(lines, start=1):
16+
record = dict(zip(headers, line))
1417
try:
15-
stock = line.split(',')
16-
num_of_shares = int(stock[1])
17-
stock_price = float(stock[2].strip())
18-
cost += (num_of_shares * stock_price)
18+
nshares = int(record['shares'])
19+
price = float(record['price'])
20+
total_cost += nshares * price
21+
# This catches errors in int() and float() conversions above
1922
except ValueError:
20-
print('Bad line', line)
23+
print(f'Row {lineno}: Bad row: {line}')
2124

2225
f.close()
23-
return cost
26+
return total_cost
2427

2528

2629
if len(sys.argv) == 2:
2730
filename = sys.argv[1]
2831
else:
29-
filename = 'Data/portfolio.csv'
32+
filename = 'Data/portfoliodate.csv'
3033

3134
cost = portfolio_cost(filename)
3235
print('Total cost:', cost)

‎Work/report.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ def read_portfolio(filename):
1010
rows = csv.reader(f)
1111
headers = next(rows)
1212
for row in rows:
13-
holding = {'name': row[0], 'shares': int(row[1]), 'price': float(row[2])}
13+
record = dict(zip(headers, row))
14+
holding = record
1415
portfolio.append(holding)
1516
return portfolio
1617

@@ -34,9 +35,9 @@ def make_report(portfolio, prices):
3435

3536
for holding in portfolio:
3637
name = holding['name']
37-
shares = holding['shares']
38+
shares = int(holding['shares'])
3839
price = prices[name]
39-
change = price - holding['price']
40+
change = price - float(holding['price'])
4041
updated_portfolio.append((name, shares, price, change))
4142

4243
return updated_portfolio
@@ -54,7 +55,7 @@ def print_report(report):
5455
print(f'{name:>10s} {shares:>10d} {money:>10s} {change:>10.2f}')
5556

5657

57-
portfolio = read_portfolio('Data/portfolio.csv')
58+
portfolio = read_portfolio('Data/portfoliodate.csv')
5859
prices = read_prices('Data/prices.csv')
5960
report = make_report(portfolio, prices)
6061
print_report(report)

0 commit comments

Comments
 (0)