Initial commit
This commit is contained in:
32
Solutions/5_3/reader.py
Normal file
32
Solutions/5_3/reader.py
Normal file
@@ -0,0 +1,32 @@
|
||||
# reader.py
|
||||
|
||||
import csv
|
||||
|
||||
def convert_csv(lines, converter, *, headers=None):
|
||||
rows = csv.reader(lines)
|
||||
if headers is None:
|
||||
headers = next(rows)
|
||||
return list(map(lambda row: converter(headers, row), rows))
|
||||
|
||||
def csv_as_dicts(lines, types, *, headers=None):
|
||||
return convert_csv(lines,
|
||||
lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) })
|
||||
|
||||
def csv_as_instances(lines, cls, *, headers=None):
|
||||
return convert_csv(lines,
|
||||
lambda headers, row: cls.from_row(row))
|
||||
|
||||
def read_csv_as_dicts(filename, types, *, headers=None):
|
||||
'''
|
||||
Read CSV data into a list of dictionaries with optional type conversion
|
||||
'''
|
||||
with open(filename) as file:
|
||||
return csv_as_dicts(file, types, headers=headers)
|
||||
|
||||
def read_csv_as_instances(filename, cls, *, headers=None):
|
||||
'''
|
||||
Read CSV data into a list of instances
|
||||
'''
|
||||
with open(filename) as file:
|
||||
return csv_as_instances(file, cls, headers=headers)
|
||||
|
||||
51
Solutions/5_3/stock.py
Normal file
51
Solutions/5_3/stock.py
Normal file
@@ -0,0 +1,51 @@
|
||||
# stock.py
|
||||
|
||||
class Stock:
|
||||
__slots__ = ('name','_shares','_price')
|
||||
_types = (str, int, float)
|
||||
def __init__(self, name, shares, price):
|
||||
self.name = name
|
||||
self.shares = shares
|
||||
self.price = price
|
||||
|
||||
def __repr__(self):
|
||||
# Note: The !r format code produces the repr() string
|
||||
return f'{type(self).__name__}({self.name!r}, {self.shares!r}, {self.price!r})'
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, Stock) and ((self.name, self.shares, self.price) ==
|
||||
(other.name, other.shares, other.price))
|
||||
|
||||
@classmethod
|
||||
def from_row(cls, row):
|
||||
values = [func(val) for func, val in zip(cls._types, row)]
|
||||
return cls(*values)
|
||||
|
||||
@property
|
||||
def shares(self):
|
||||
return self._shares
|
||||
@shares.setter
|
||||
def shares(self, value):
|
||||
if not isinstance(value, self._types[1]):
|
||||
raise TypeError(f'Expected {self._types[1].__name__}')
|
||||
if value < 0:
|
||||
raise ValueError('shares must be >= 0')
|
||||
self._shares = value
|
||||
|
||||
@property
|
||||
def price(self):
|
||||
return self._price
|
||||
@price.setter
|
||||
def price(self, value):
|
||||
if not isinstance(value, self._types[2]):
|
||||
raise TypeError(f'Expected {self._types[2].__name__}')
|
||||
if value < 0:
|
||||
raise ValueError('price must be >= 0')
|
||||
self._price = value
|
||||
|
||||
@property
|
||||
def cost(self):
|
||||
return self.shares * self.price
|
||||
|
||||
def sell(self, nshares):
|
||||
self.shares -= nshares
|
||||
Reference in New Issue
Block a user