Added solution code

This commit is contained in:
David Beazley
2020-05-27 17:03:35 -05:00
parent 960d4fa2fa
commit 5b6f15db17
136 changed files with 5828 additions and 350 deletions

32
Solutions/2_16/pcost.py Normal file
View File

@@ -0,0 +1,32 @@
# pcost.py
import csv
def portfolio_cost(filename):
'''
Computes the total cost (shares*price) of a portfolio file
'''
total_cost = 0.0
with open(filename) as f:
rows = csv.reader(f)
headers = next(rows)
for rowno, row in enumerate(rows, start=1):
record = dict(zip(headers, row))
try:
nshares = int(record['shares'])
price = float(record['price'])
total_cost += nshares * price
# This catches errors in int() and float() conversions above
except ValueError:
print(f'Row {rowno}: Bad row: {row}')
return total_cost
import sys
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
filename = input('Enter a filename:')
cost = portfolio_cost(filename)
print('Total cost:', cost)