0% found this document useful (0 votes)
16 views62 pages

Chapter 2 Exercises

The document contains a series of exercises focused on programming concepts, including classes for managing flowers and credit cards. It demonstrates the implementation of methods for setting and getting attributes, handling invalid inputs, and managing balances. Additionally, it showcases the use of inheritance in creating specialized credit card classes with specific functionalities.

Uploaded by

Pinaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views62 pages

Chapter 2 Exercises

The document contains a series of exercises focused on programming concepts, including classes for managing flowers and credit cards. It demonstrates the implementation of methods for setting and getting attributes, handling invalid inputs, and managing balances. Additionally, it showcases the use of inheritance in creating specialized credit card classes with specific functionalities.

Uploaded by

Pinaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Chapter 2 Exercises

Reinforcement
In [1]:
#---------R2-1-------------------
"""
1) Software for monitoring vitals

2) Self-driving cars

3) Insulin Pump

"""
Out[1]:
'\n1) Software for monitoring vitals\n\n2) Self-driving cars\n\n3) Insulin
Pump\n\n'
In [2]:
#--------R2-2----------------
"""
Software that estimates market demand for a product so that you don't
overproduce a component as it becomes less desirable in the marketplace

"""
Out[2]:
"\nSoftware that estimates market demand for a product so that you don't \n
overproduce a component as it becomes less desirable in the marketplace\n\n
"
In [3]:
#---------R2-3--------------
"""
Saving a file:
- Check whether a file exists
- Start the i/o stream
- Write the data to a file
- Close the i/0 stream
- Handle different extensions and encodings
- Provide a dialog box for user inputs
- Handle invalid inputs

"""
Out[3]:
'\nSaving a file:\n- Check whether a file exists\n- Start the i/o stream\n-
Write the data to a file\n- Close the i/0 stream\n- Handle different extens
ions and encodings\n- Provide a dialog box for user inputs\n- Handle invali
d inputs\n\n'
In [4]:
#--------R2-4-------------

class Flower():
def __init__(self, name = None, petals = None, price = None):
self._name = self._petals = self._price = None
self.set_name(name)
self.set_petals(petals)
self.set_price(price)

def set_name(self, name):


try:
self._name = str(name)
except:
print ('Invalid input for a name, it must be a string')

def set_petals(self, petals):


try:
self._petals = petals
except:
print ('Invalid input')

def set_price(self, price):


if price is not None:
try:
self._price = float(price)
except:
print ('Invalid price, must be a number (no dollar sign)')

def get_name(self):
if self._name is None: return ('Attribute has not been set')
else: return self._name

def get_price(self):
if self._price is None: return ('Attribute has not been set')
else: return self._price

def get_petals(self):
if self._petals is None: return ('Attribute has not been set')
else: return self._petals

Dand = Flower('Dandelion', 5, '$10.32')


print(Dand.get_name(), Dand.get_petals(), Dand.get_price())

print ('\n')
Rose = Flower()
print(Rose.get_name(), Rose.get_petals(), Rose.get_price())

Rose.set_name('Rose')
Rose.set_price(20)
Rose.set_petals(30)
print(Rose.get_name(), Rose.get_petals(), Rose.get_price())

Invalid price, must be a number (no dollar sign)


Dandelion 5 Attribute has not been set
None Attribute has not been set Attribute has not been set
Rose 30 20.0
In [5]:
#-----------R2.5-------------------
class CreditCard():
def __init__(self, customer, bank, acnt, limit):
self._customer = customer
self._bank = bank
self._account = acnt
self._limit = limit
self._balance = 0 #Start with a balance of zero

def get_customer(self):
return self._customer
def get_bank(self):
return self._bank
def get_account(self):
return self._account
def get_limit(self):
return self._limit
def get_balance(self):
return self._balance

def set_balance(self, value):


self._balance = value

def charge(self, price):


try:
price = float(price) #This will accept an int, float or string
that can be converted to a float
except:
print ('Invalid input')
return False
if price+self._balance >self._limit:
print(f'Your deposit of {price} exceeds your remainder of
{self.get_limit()-self.get_balance()}')
return False #You are going over your limit
else:
self._balance += price
return True

def make_payment(self, amount):


try:
amount = float(amount) #This will accept an int, float or
string that can be converted to a float
except:
print ('Invalid input')
return False
self._balance -= amount
return True

cc1 = CreditCard('Andrew', 'ABC', '1234567890', 1000)


cc1.make_payment(100); print(cc1.get_balance())
cc1.charge(100); print(cc1.get_balance())
cc1.charge(500); print(cc1.get_balance())
cc1.charge(200); print(cc1.get_balance())
cc1.charge(100); print(cc1.get_balance())
cc1.charge(500); print(cc1.get_balance())
cc1.charge("Hello"); print(cc1.get_balance())
cc1.charge("20"); print(cc1.get_balance())
cc1.charge("453.4"); print(cc1.get_balance())
-100.0
0.0
500.0
700.0
800.0
Your deposit of 500.0 exceeds your remainder of 200.0
800.0
Invalid input
800.0
820.0
Your deposit of 453.4 exceeds your remainder of 180.0
820.0
In [6]:
#------------R2.6----------------------
class CreditCardWithoutNegatives(CreditCard):
def make_payment(self, amount):
try:
amount = float(amount)
except:
print('Invalid Input')
return False

if amount < 0:
raise ValueError('Cannot make negative payments. Try the
charge method')
else:
self._balance -= amount
return True

cc1 = CreditCardWithoutNegatives('Andrew', 'ABC', '1234567890', 1000)


cc1.make_payment(100); print(cc1.get_balance())
cc1.charge(100); print(cc1.get_balance())
cc1.charge(500); print(cc1.get_balance())
cc1.charge(200); print(cc1.get_balance())
cc1.charge(100); print(cc1.get_balance())
cc1.charge(500); print(cc1.get_balance())
cc1.charge("Hello"); print(cc1.get_balance())
cc1.charge("20"); print(cc1.get_balance())
cc1.charge("453.4"); print(cc1.get_balance())
try:
cc1.make_payment("-453.4"); print(cc1.get_balance())
except Exception as e:
print (e)

-100.0
0.0
500.0
700.0
800.0
Your deposit of 500.0 exceeds your remainder of 200.0
800.0
Invalid input
800.0
820.0
Your deposit of 453.4 exceeds your remainder of 180.0
820.0
Cannot make negative payments. Try the charge method
In [7]:
#--------------R2.7--------------------------
#Note, you must run the cell in R2-4 for this one to work
class CreditCardWithBalance(CreditCard):
def __init__(self, customer, bank, acnt, limit, balance = 0):
super().__init__(customer, bank, acnt, limit)
self._balance = balance

cc1 = CreditCardWithBalance('Andrew', 'ABC', '1234567890', 1000, 50)


cc1.make_payment(100); print(cc1.get_balance())
cc1.charge(100); print(cc1.get_balance())
cc1.charge(500); print(cc1.get_balance())
cc1.charge(200); print(cc1.get_balance())
cc1.charge(100); print(cc1.get_balance())
cc1.charge(500); print(cc1.get_balance())
cc1.charge("Hello"); print(cc1.get_balance())
cc1.charge("20"); print(cc1.get_balance())
cc1.charge("453.4"); print(cc1.get_balance())
-50.0
50.0
550.0
750.0
850.0
Your deposit of 500.0 exceeds your remainder of 150.0
850.0
Invalid input
850.0
870.0
Your deposit of 453.4 exceeds your remainder of 130.0
870.0
In [8]:
#----------------R2.8------------------------
#Note: Must run the credit card class creation from R2.5
class CreditCardSelfReport(CreditCard):
def special_charge(self, amount):
if super().charge(amount): return True
else:
print ("Credit card has failed:", self.get_bank())

wallet = []
wallet.append(CreditCardSelfReport('John Bowman' , 'California Savings'
,'56 5391 0375 9387 5309' , 2500))
wallet.append(CreditCardSelfReport('John Bowman' , 'California Federal'
,'3485 0399 3395 1954' , 3500))
wallet.append(CreditCardSelfReport('John Bowman' , 'California Finance'
,'5391 0375 9387 5309' , 5000))
for val in range (1,100):
wallet[0].special_charge(val)
wallet[1].special_charge(2*val)
wallet[2].special_charge(3*val)

for c in range(3):
print ('Customer = ', wallet[c].get_customer())
print ('Bank = ', wallet[c].get_bank())
print('Account = ', wallet[c].get_account())
print ('Limit = ', wallet[c].get_limit())
print('Balance = ', wallet[c].get_balance())
while wallet[c].get_balance()>100:
wallet[c].make_payment(100)
print('New Balance = ', wallet[c].get_balance())
print()
Your deposit of 174.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 118.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 177.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 120.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 180.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 122.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 183.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 124.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 186.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 126.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 189.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 128.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 192.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 130.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 195.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 132.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 198.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 134.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 201.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 136.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 204.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 138.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 207.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 140.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 210.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 71.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 142.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 213.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 72.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 144.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 216.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 73.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 146.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 219.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 74.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 148.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 222.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 75.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 150.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 225.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 76.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 152.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 228.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 77.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 154.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 231.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 78.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 156.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 234.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 79.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 158.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 237.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 80.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 160.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 240.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 81.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 162.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 243.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 82.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 164.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 246.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 83.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 166.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 249.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 84.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 168.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 252.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 85.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 170.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 255.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 86.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 172.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 258.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 87.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 174.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 261.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 88.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 176.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 264.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 89.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 178.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 267.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 90.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 180.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 270.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 91.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 182.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 273.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 92.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 184.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 276.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 93.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 186.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 279.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 94.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 188.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 282.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 95.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 190.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 285.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 96.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 192.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 288.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 97.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 194.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 291.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 98.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 196.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 294.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Your deposit of 99.0 exceeds your remainder of 15.0
Credit card has failed: California Savings
Your deposit of 198.0 exceeds your remainder of 78.0
Credit card has failed: California Federal
Your deposit of 297.0 exceeds your remainder of 41.0
Credit card has failed: California Finance
Customer = John Bowman
Bank = California Savings
Account = 56 5391 0375 9387 5309
Limit = 2500
Balance = 2485.0
New Balance = 2385.0
New Balance = 2285.0
New Balance = 2185.0
New Balance = 2085.0
New Balance = 1985.0
New Balance = 1885.0
New Balance = 1785.0
New Balance = 1685.0
New Balance = 1585.0
New Balance = 1485.0
New Balance = 1385.0
New Balance = 1285.0
New Balance = 1185.0
New Balance = 1085.0
New Balance = 985.0
New Balance = 885.0
New Balance = 785.0
New Balance = 685.0
New Balance = 585.0
New Balance = 485.0
New Balance = 385.0
New Balance = 285.0
New Balance = 185.0
New Balance = 85.0

Customer = John Bowman


Bank = California Federal
Account = 3485 0399 3395 1954
Limit = 3500
Balance = 3422.0
New Balance = 3322.0
New Balance = 3222.0
New Balance = 3122.0
New Balance = 3022.0
New Balance = 2922.0
New Balance = 2822.0
New Balance = 2722.0
New Balance = 2622.0
New Balance = 2522.0
New Balance = 2422.0
New Balance = 2322.0
New Balance = 2222.0
New Balance = 2122.0
New Balance = 2022.0
New Balance = 1922.0
New Balance = 1822.0
New Balance = 1722.0
New Balance = 1622.0
New Balance = 1522.0
New Balance = 1422.0
New Balance = 1322.0
New Balance = 1222.0
New Balance = 1122.0
New Balance = 1022.0
New Balance = 922.0
New Balance = 822.0
New Balance = 722.0
New Balance = 622.0
New Balance = 522.0
New Balance = 422.0
New Balance = 322.0
New Balance = 222.0
New Balance = 122.0
New Balance = 22.0

Customer = John Bowman


Bank = California Finance
Account = 5391 0375 9387 5309
Limit = 5000
Balance = 4959.0
New Balance = 4859.0
New Balance = 4759.0
New Balance = 4659.0
New Balance = 4559.0
New Balance = 4459.0
New Balance = 4359.0
New Balance = 4259.0
New Balance = 4159.0
New Balance = 4059.0
New Balance = 3959.0
New Balance = 3859.0
New Balance = 3759.0
New Balance = 3659.0
New Balance = 3559.0
New Balance = 3459.0
New Balance = 3359.0
New Balance = 3259.0
New Balance = 3159.0
New Balance = 3059.0
New Balance = 2959.0
New Balance = 2859.0
New Balance = 2759.0
New Balance = 2659.0
New Balance = 2559.0
New Balance = 2459.0
New Balance = 2359.0
New Balance = 2259.0
New Balance = 2159.0
New Balance = 2059.0
New Balance = 1959.0
New Balance = 1859.0
New Balance = 1759.0
New Balance = 1659.0
New Balance = 1559.0
New Balance = 1459.0
New Balance = 1359.0
New Balance = 1259.0
New Balance = 1159.0
New Balance = 1059.0
New Balance = 959.0
New Balance = 859.0
New Balance = 759.0
New Balance = 659.0
New Balance = 559.0
New Balance = 459.0
New Balance = 359.0
New Balance = 259.0
New Balance = 159.0
New Balance = 59.0

In [9]:
#-----------R2-9--------------------
class Vector:
def __init__(self, d):
self._coords = [0]*d
def __len__(self):
return len(self._coords)
def __getitem__(self, j):
return self._coords[j]
def __setitem__(self, j, val):
try:
self._coords[j] = val
return True
except:
print('Invalid input or index')
return False
def __add__(self, other):
if len(self)!=len(other):
raise ValueError('Dimensions must match')
result = Vector(len(self))
for j in range(len(self)):
result[j] = self[j] + other[j]
return result

def __eq__(self, other):


return self._coords == other._coords

def __ne__(self, other):


return not self==other

def __str__(self):
return '<' + str(self._coords)[1:-1] + '>'

def __sub__(self, other):


if len(self) != len(other):
raise ValueError('Dimensions must match')
result = Vector(len(self))
for j in range (len(self)):
result[j] = self[j] - other[j]
return result

v1 = Vector(5)
v2 = Vector (5)
for i in range(5):
v1[i] = 5
v2[i] = i

print (v1+v2)
print (v1-v2)
print (v2-v1)

<5, 6, 7, 8, 9>
<5, 4, 3, 2, 1>
<-5, -4, -3, -2, -1>
In [10]:
#-------------R2-10--------------
class VectorwNeg(Vector):
def __neg__(self):
result = Vector(len(self))
for i in range(len(self)):
result[i] = -self[i]
return result

vv = VectorwNeg #Use this so that I can easily change the class for
subsequent exercises

v1 = vv(5)
v2 = vv(5)
for i in range(5):
v1[i] = 5
v2[i] = i

print (v1+v2)
print (v1-v2)
print (v2-v1)
print (-v1, v1)
<5, 6, 7, 8, 9>
<5, 4, 3, 2, 1>
<-5, -4, -3, -2, -1>
<-5, -5, -5, -5, -5> <5, 5, 5, 5, 5>
In [11]:
#--------------R2-11------------------
"""
If the method list.add fails, the method in Vector.radd will be checked
instead.
Adding a def __radd__(self, other): would allow you to solve that problem
One option would be to use an iterator to go through each of the components
and add them
(since __len__ and __getitem__ should be defined for each class)
"""
Out[11]:
'\nIf the method list.add fails, the method in Vector.radd will be checked
instead.\nAdding a def __radd__(self, other): would allow you to solve that
problem\nOne option would be to use an iterator to go through each of the c
omponents and add them \n(since __len__ and __getitem__ should be defined f
or each class) \n\n'
In [12]:
#----------R2-12-----------------
class VectorwMult(VectorwNeg):
def __mul__(self, value):
result = Vector(len(self))
for i in range(len(self)):
result[i] = self[i]*value
return result

vv = VectorwMult

v1 = vv(5)
v2 = vv(5)
for i in range(5):
v1[i] = 5
v2[i] = i

print (v1+v2)
print (v1-v2)
print (v2-v1)
print (-v1, v1)
print (v1*6)
<5, 6, 7, 8, 9>
<5, 4, 3, 2, 1>
<-5, -4, -3, -2, -1>
<-5, -5, -5, -5, -5> <5, 5, 5, 5, 5>
<30, 30, 30, 30, 30>
In [13]:
#----------R2-13-------------
class VectorwrMult(VectorwMult):
def __rmul__(self, value):
return (self * value) #Treat it like vector*value instead of
value*vector

vv = VectorwrMult

v1 = vv(5)
v2 = vv(5)
for i in range(5):
v1[i] = 5
v2[i] = i

print (v1+v2)
print (v1-v2)
print (v2-v1)
print (-v1, v1)
print (v1*6)
print (7*v1)
<5, 6, 7, 8, 9>
<5, 4, 3, 2, 1>
<-5, -4, -3, -2, -1>
<-5, -5, -5, -5, -5> <5, 5, 5, 5, 5>
<30, 30, 30, 30, 30>
<35, 35, 35, 35, 35>
In [14]:
#----------R2-14----------------
class VectorwVectorMult(VectorwrMult):
def __mul__(self, other): #Overriding the original definition
if type(other) == int or type(other) == float:
result = Vector(len(self))
for i in range(len(self)):
result[i] = self[i]*other
return result

else:
len(other)
print (len(other), len(self))
if len(other) != len(self):
raise ValueError('Vector lengths do not match')
sum = 0
for i in range(len(self)):
sum += self[i]*other[i]
return sum

vv = VectorwVectorMult

v1 = vv(5)
v2 = vv(5)
for i in range(5):
v1[i] = 5
v2[i] = i

print (v1+v2)
print (v1-v2)
print (v2-v1)
print (-v1, v1)
print (v1*6)
print (7*v1)
print (v1*v2)
try:
print (v1*vv(7))
except Exception as e:
print(e)
print (v1*3.3)
<5, 6, 7, 8, 9>
<5, 4, 3, 2, 1>
<-5, -4, -3, -2, -1>
<-5, -5, -5, -5, -5> <5, 5, 5, 5, 5>
<30, 30, 30, 30, 30>
<35, 35, 35, 35, 35>
5 5
50
7 5
Vector lengths do not match
<16.5, 16.5, 16.5, 16.5, 16.5>
In [15]:
#--------R2-15----------------
class VectorwListInit(VectorwVectorMult):
def __init__(self, param): #Override the original constructor
if isinstance(param, int):
super().__init__(param)
else:
self._coords = param

vv = VectorwListInit

v1 = vv(5)
v2 = vv(5)
for i in range(5):
v1[i] = 5
v2[i] = i

print (v1+v2)
print (v1-v2)
print (v2-v1)
print (-v1, v1)
print (v1*6)
print (7*v1)
print (v1*v2)
try:
print (v1*vv(7))
except Exception as e:
print(e)
print (v1*3.3)
print (vv([1,2,3]), vv(3))
<5, 6, 7, 8, 9>
<5, 4, 3, 2, 1>
<-5, -4, -3, -2, -1>
<-5, -5, -5, -5, -5> <5, 5, 5, 5, 5>
<30, 30, 30, 30, 30>
<35, 35, 35, 35, 35>
5 5
50
7 5
Vector lengths do not match
<16.5, 16.5, 16.5, 16.5, 16.5>
<1, 2, 3> <0, 0, 0>
In [16]:
#------------R2-16-----------
"""
ex. (0,10,1) -> max(0, 5)
ex. (0, 11, 1) -> max(0, (11//2)) -> (0, 5)
ex. (0, 1, 2) -> max(0, (2//2)) -> max(0,1)
ex. (0,0,1) -> max(0, 0) -> max(0, 0)
ex. (0, 1, -2) -> max(0, (-2//2)) -> max(0, -1)

The max(0, ...) is to account for cases where the step size means that
the stop value is actually "further away" from the start value
Adding the (+ step -1) ensures that you include a step that has less than a
full step size between itself and the stop value
ex (the 6 in range(0, 7)). The -1 prevents it from adding an extra number
to the iterator

"""
Out[16]:
'\nex. (0,10,1) -> max(0, 5)\nex. (0, 11, 1) -> max(0, (11//2)) -> (0, 5)\n
ex. (0, 1, 2) -> max(0, (2//2)) -> max(0,1)\nex. (0,0,1) -> max(0, 0) -> ma
x(0, 0)\nex. (0, 1, -2) -> max(0, (-2//2)) -> max(0, -1)\n\nThe max(0, ...)
is to account for cases where the step size means that\n the stop value is
actually "further away" from the start value\n \nAdding the (+ step -1) ens
ures that you include a step that has less than a full step size between it
self and the stop value\nex (the 6 in range(0, 7)). The -1 prevents it fro
m adding an extra number to the iterator\n \n\n'
In [17]:
#------------R2-17---------------------
"""
Object
/ | \
Horse Goat Pig
/ \
Racer Equestrian

example Class Diagrma


|-------------------------|
|Class: Horse |
|-------------------------|
| Fields: |
| _height |
| _color |
|-------------------------|
| Behaviours: |
| run() |
| jump() |
|-------------------------|

"""
Out[17]:
'\n Object\n / | Horse Goat P
ig\n / Racer Equestrian\n \n \n \n example Class Diagrma\n|---
----------------------|\n|Class: Horse |\n|--------------------
-----|\n| Fields: |\n| _height |\n| _color
|\n|-------------------------|\n| Behaviours: |\n| run()
|\n| jump() |\n|-------------------------|\n\n'
In [18]:
#-------------R2-18------------
class Progression():
def __init__(self, start=0):
self._current = 0
def _advance(self):
self._current += 1
def __next__(self):
if self._current is None:
raise StopIteration()
else:
answer = self._current
self._advance()
return answer
def __iter__(self):
return self
def print_progression(self, n):
print (' '.join(str(next(self)) for j in range(n)))

class Fibonacci(Progression):
def __init__(self, first = 0, second = 1):
self._current = first
self._previous = second - first

def __next__(self):
answer = self._current
self._current, self._previous = self._current+self._previous,
self._current
return answer

def __getitem__(self, item): #Note, not check against negative numbers


current = self._current
previous = self._previous

for i in range(item+1):
answer = next(self)

self._current, self._previous = current, previous #Restore the


original values
return answer

p = Progression()
p.print_progression(10)

f = Fibonacci(2,2)
for i in range (8):
print (f'Value Number {i+1} is {f[i]}')
f.print_progression(8)
0 1 2 3 4 5 6 7 8 9
Value Number 1 is 2
Value Number 2 is 2
Value Number 3 is 4
Value Number 4 is 6
Value Number 5 is 10
Value Number 6 is 16
Value Number 7 is 26
Value Number 8 is 42
2 2 4 6 10 16 26 42
In [19]:
#------------R2-19----------------
#Note, this answer relies on the Progression class from R2-18

class ArithmeticProgression(Progression):
def __init__(self, start=0, step = 1):
self._current = start
self._step = step

def __next__(self):
answer = self._current
self._current = self._current + self._step
return answer

def __getitem__(self, index):


current = self._current
for i in range(index + 1):
answer = next(self)
self._current = current
return (answer)

p = Progression()
p.print_progression(10)

a = ArithmeticProgression(1,1)
for i in range (8):
print (f'Value Number {i+1} is {a[i]}')
a.print_progression(8)

#Note, the code below would take too long to run. The answer is
2**63//128, which is 7.2e16 calls
"""
b = ArithmeticProgression(0, 128)
i = 0
goal = 2**63
value = 0
while value < goal:
i+=1
value = next(b)
print (f'It requires {i-1} iterations to get to 2**63')
"""
0 1 2 3 4 5 6 7 8 9
Value Number 1 is 1
Value Number 2 is 2
Value Number 3 is 3
Value Number 4 is 4
Value Number 5 is 5
Value Number 6 is 6
Value Number 7 is 7
Value Number 8 is 8
1 2 3 4 5 6 7 8
Out[19]:
"\nb = ArithmeticProgression(0, 128)\ni = 0\ngoal = 2**63\nvalue = 0\nwhile
value < goal:\n i+=1\n value = next(b)\nprint (f'It requires {i-1} it
erations to get to 2**63')\n"
In [20]:
#----------R2-20------------------
"""
If behaviour changes in A without D knowing (ex. different teams or people
working on it),
it can be very difficult to troubleshoot the problems
You also have a larger chance of namespace conflicts that you aren't aware
of
(ex. C overrides a function from B that you don't know about)
"""
Out[20]:
"\nIf behaviour changes in A without D knowing (ex. different teams or peop
le working on it), \nit can be very difficult to troubleshoot the problems\
n\n\nYou also have a larger chance of namespace conflicts that you aren't a
ware of \n(ex. C overrides a function from B that you don't know about)\n"
In [21]:
#-----------R2-21--------------
"""
If any of the classes change, it will mess up the entire Z subclass

Namespace conflicts are probable more difficult to resolve?? Not sure


about that one

"""
Out[21]:
'\nIf any of the classes change, it will mess up the entire Z subclass\n\nN
amespace conflicts are probable more difficult to resolve?? Not sure about
that one\n\n'
In [22]:
#-----------R2-22------------
from abc import ABCMeta, abstractmethod

class Sequence(metaclass = ABCMeta):


@abstractmethod
def __len__(self):
pass

@abstractmethod
def __getitem__(self, index):
pass

def __contains__(self, val):


for i in range(len(self)):
if self[j] == val: return True
return False #if it wasn't found

def count(self, val):


k = 0
for j in range(len(self)):
if self[j] == val: k+=1
return k

def __eq__(self, other):


#Note, assume that they have to be equal and have the same number
of elements (a little ambiguous in the question)
#otherwise, the range would be min(len(self), len(other))
if len(self) != len (other):
return False
else:
for i in range(len(self)):
if self[i] != other[i]:
return False
return True #If you made it through, all the elements are the
same

In [23]:
#-----------R2-23------------

class Sequence(metaclass = ABCMeta):


@abstractmethod
def __len__(self):
pass

@abstractmethod
def __getitem__(self, index):
pass

def __contains__(self, val):


for i in range(len(self)):
if self[j] == val: return True
return False #if it wasn't found

def count(self, val):


k = 0
for j in range(len(self)):
if self[j] == val: k+=1
return k

def __lt__(self, other):


for i in range(min(len(self), len(other))):
if self[i] != other[i]: return False
return True

Creativity
In [24]:
#----------C2-24--------------------
"""
Methods:
purchase_books()
view_purchased()
read_purchased()

Class Hierarchy:
E-book Class -> Class for a specific model (Different models may have
different features)
Book Class (Nested or not)

"""
Out[24]:
'\nMethods:\npurchase_books()\nview_purchased()\nread_purchased()\n\n\nClas
s Hierarchy:\nE-book Class -> Class for a specific model (Different models
may have different features)\nBook Class (Nested or not)\n\n\n'
In [25]:
#------------C2-25-----------------
""" See R2-14 """
Out[25]:
' See R2-14 '
In [26]:
#----------C2-26----------------
class SequenceIterator():
def __init__(self, sequence):
self._seq = sequence
self._k = -1

def __next__(self):
self._k += 1
if self._k <len(self._seq):
return (self._seq[self._k])
else:
raise StopIteration()

def __iter__(self):
return self

class ReverseSequenceIterator():
def __init__(self, sequence):
self._seq = sequence
self._k = len(sequence)

def __next__(self):
self._k -= 1
if self._k >=0:
return self._seq[self._k]
else:
raise StopIteration()

def __iter__(self):
return self

s = ReverseSequenceIterator([1,2,3,4,5, 6, 7, 8])

print([x for x in ReverseSequenceIterator([1,2,3,4,5, 6, 7, 8])])

print([x for x in ReverseSequenceIterator([1,2,'d',4,56, 7, 8])])


[8, 7, 6, 5, 4, 3, 2, 1]
[8, 7, 56, 4, 'd', 2, 1]
In [27]:
#---------------C-27-------------
class Range():
def __init__(self, start, stop = None, step = 1):
if step == 0: raise ValueError('step cannot be 0')
if stop is None: #This is more robust than if stop == None,
since it's ambiguous sometimes (ex. custom classes)
start, stop = 0, start
self._length = max(0, (stop-start + step -1)//step)

self._start = start
self._step = step

def __len__(self):
return self._length

def __getitem__(self, k):


if k<0:
k+= len(self)
if not 0<=k<self._length:
raise IndexError('index out of range')

return self._start + k*self._step

def __contains__(self, value):


# The number will be in the sequence if (value - start)% step == 0
factor, remainder = divmod((value-self._start), self._step)

if remainder == 0: #It is a part of the infinite range in either


directiom
#Now we just need to check if it's within the defined range...
if factor < len(self) and factor >=0: return True
else: return False
else:
return False

r = Range(1,100,2)
print (len(r), r[3], 4 in r, 5 in r)

r = Range(-100, step = -1)


print (len(r), r[3], 4 in r, 5 in r)
50 7 False True
102 -3 False False
In [28]:
#-------------C-28--------------
#Note, this relies on you running the Credit Card class definition form R2-
5 above

class PredatoryCreditCard(CreditCard):
MAX_CHARGES = 10
def __init__(self, customer, bank, acnt, limit, apr):
super().__init__(customer, bank, acnt, limit)
self._apr = apr
self._num_charges = 0

def charge(self, price):


success = super().charge(price)
if not success:
self._balance += 5
else:
self._num_charges += 1
if self._num_charges > self.MAX_CHARGES:
self._balance+=1

return success

def process_month(self):
if self._balance >0:
monthly_factor = pow(1+self._apr, 1/12)
self._balance *= monthly_factor
self._num_charges = 0 #reset the counter at the beginning of each
month

wallet = []
wallet.append(PredatoryCreditCard('John Bowman' , 'California Savings' ,'56
5391 0375 9387 5309' , 2500, 0.15))
wallet.append(PredatoryCreditCard('John Bowman' , 'California Federal'
,'3485 0399 3395 1954' , 3500, 0.15))
wallet.append(PredatoryCreditCard('John Bowman' , 'California Finance'
,'5391 0375 9387 5309' , 5000, 0.30))

for val in range (1,100):


wallet[0].charge(val)
wallet[1].charge(2*val)
wallet[2].charge(3*val)

for c in range(3):
print ('Customer = ', wallet[c].get_customer())
print ('Bank = ', wallet[c].get_bank())
print('Account = ', wallet[c].get_account())
print ('Limit = ', wallet[c].get_limit())
print('Balance = ', wallet[c].get_balance())
while wallet[c].get_balance()>100:
wallet[c].make_payment(100)
print('New Balance = ', wallet[c].get_balance())
print()

Your deposit of 171.0 exceeds your remainder of 166.0


Your deposit of 174.0 exceeds your remainder of 161.0
Your deposit of 118.0 exceeds your remainder of 30.0
Your deposit of 177.0 exceeds your remainder of 156.0
Your deposit of 120.0 exceeds your remainder of 25.0
Your deposit of 180.0 exceeds your remainder of 151.0
Your deposit of 122.0 exceeds your remainder of 20.0
Your deposit of 183.0 exceeds your remainder of 146.0
Your deposit of 124.0 exceeds your remainder of 15.0
Your deposit of 186.0 exceeds your remainder of 141.0
Your deposit of 126.0 exceeds your remainder of 10.0
Your deposit of 189.0 exceeds your remainder of 136.0
Your deposit of 128.0 exceeds your remainder of 5.0
Your deposit of 192.0 exceeds your remainder of 131.0
Your deposit of 130.0 exceeds your remainder of 0.0
Your deposit of 195.0 exceeds your remainder of 126.0
Your deposit of 132.0 exceeds your remainder of -5.0
Your deposit of 198.0 exceeds your remainder of 121.0
Your deposit of 134.0 exceeds your remainder of -10.0
Your deposit of 201.0 exceeds your remainder of 116.0
Your deposit of 136.0 exceeds your remainder of -15.0
Your deposit of 204.0 exceeds your remainder of 111.0
Your deposit of 138.0 exceeds your remainder of -20.0
Your deposit of 207.0 exceeds your remainder of 106.0
Your deposit of 70.0 exceeds your remainder of 26.0
Your deposit of 140.0 exceeds your remainder of -25.0
Your deposit of 210.0 exceeds your remainder of 101.0
Your deposit of 71.0 exceeds your remainder of 21.0
Your deposit of 142.0 exceeds your remainder of -30.0
Your deposit of 213.0 exceeds your remainder of 96.0
Your deposit of 72.0 exceeds your remainder of 16.0
Your deposit of 144.0 exceeds your remainder of -35.0
Your deposit of 216.0 exceeds your remainder of 91.0
Your deposit of 73.0 exceeds your remainder of 11.0
Your deposit of 146.0 exceeds your remainder of -40.0
Your deposit of 219.0 exceeds your remainder of 86.0
Your deposit of 74.0 exceeds your remainder of 6.0
Your deposit of 148.0 exceeds your remainder of -45.0
Your deposit of 222.0 exceeds your remainder of 81.0
Your deposit of 75.0 exceeds your remainder of 1.0
Your deposit of 150.0 exceeds your remainder of -50.0
Your deposit of 225.0 exceeds your remainder of 76.0
Your deposit of 76.0 exceeds your remainder of -4.0
Your deposit of 152.0 exceeds your remainder of -55.0
Your deposit of 228.0 exceeds your remainder of 71.0
Your deposit of 77.0 exceeds your remainder of -9.0
Your deposit of 154.0 exceeds your remainder of -60.0
Your deposit of 231.0 exceeds your remainder of 66.0
Your deposit of 78.0 exceeds your remainder of -14.0
Your deposit of 156.0 exceeds your remainder of -65.0
Your deposit of 234.0 exceeds your remainder of 61.0
Your deposit of 79.0 exceeds your remainder of -19.0
Your deposit of 158.0 exceeds your remainder of -70.0
Your deposit of 237.0 exceeds your remainder of 56.0
Your deposit of 80.0 exceeds your remainder of -24.0
Your deposit of 160.0 exceeds your remainder of -75.0
Your deposit of 240.0 exceeds your remainder of 51.0
Your deposit of 81.0 exceeds your remainder of -29.0
Your deposit of 162.0 exceeds your remainder of -80.0
Your deposit of 243.0 exceeds your remainder of 46.0
Your deposit of 82.0 exceeds your remainder of -34.0
Your deposit of 164.0 exceeds your remainder of -85.0
Your deposit of 246.0 exceeds your remainder of 41.0
Your deposit of 83.0 exceeds your remainder of -39.0
Your deposit of 166.0 exceeds your remainder of -90.0
Your deposit of 249.0 exceeds your remainder of 36.0
Your deposit of 84.0 exceeds your remainder of -44.0
Your deposit of 168.0 exceeds your remainder of -95.0
Your deposit of 252.0 exceeds your remainder of 31.0
Your deposit of 85.0 exceeds your remainder of -49.0
Your deposit of 170.0 exceeds your remainder of -100.0
Your deposit of 255.0 exceeds your remainder of 26.0
Your deposit of 86.0 exceeds your remainder of -54.0
Your deposit of 172.0 exceeds your remainder of -105.0
Your deposit of 258.0 exceeds your remainder of 21.0
Your deposit of 87.0 exceeds your remainder of -59.0
Your deposit of 174.0 exceeds your remainder of -110.0
Your deposit of 261.0 exceeds your remainder of 16.0
Your deposit of 88.0 exceeds your remainder of -64.0
Your deposit of 176.0 exceeds your remainder of -115.0
Your deposit of 264.0 exceeds your remainder of 11.0
Your deposit of 89.0 exceeds your remainder of -69.0
Your deposit of 178.0 exceeds your remainder of -120.0
Your deposit of 267.0 exceeds your remainder of 6.0
Your deposit of 90.0 exceeds your remainder of -74.0
Your deposit of 180.0 exceeds your remainder of -125.0
Your deposit of 270.0 exceeds your remainder of 1.0
Your deposit of 91.0 exceeds your remainder of -79.0
Your deposit of 182.0 exceeds your remainder of -130.0
Your deposit of 273.0 exceeds your remainder of -4.0
Your deposit of 92.0 exceeds your remainder of -84.0
Your deposit of 184.0 exceeds your remainder of -135.0
Your deposit of 276.0 exceeds your remainder of -9.0
Your deposit of 93.0 exceeds your remainder of -89.0
Your deposit of 186.0 exceeds your remainder of -140.0
Your deposit of 279.0 exceeds your remainder of -14.0
Your deposit of 94.0 exceeds your remainder of -94.0
Your deposit of 188.0 exceeds your remainder of -145.0
Your deposit of 282.0 exceeds your remainder of -19.0
Your deposit of 95.0 exceeds your remainder of -99.0
Your deposit of 190.0 exceeds your remainder of -150.0
Your deposit of 285.0 exceeds your remainder of -24.0
Your deposit of 96.0 exceeds your remainder of -104.0
Your deposit of 192.0 exceeds your remainder of -155.0
Your deposit of 288.0 exceeds your remainder of -29.0
Your deposit of 97.0 exceeds your remainder of -109.0
Your deposit of 194.0 exceeds your remainder of -160.0
Your deposit of 291.0 exceeds your remainder of -34.0
Your deposit of 98.0 exceeds your remainder of -114.0
Your deposit of 196.0 exceeds your remainder of -165.0
Your deposit of 294.0 exceeds your remainder of -39.0
Your deposit of 99.0 exceeds your remainder of -119.0
Your deposit of 198.0 exceeds your remainder of -170.0
Your deposit of 297.0 exceeds your remainder of -44.0
Customer = John Bowman
Bank = California Savings
Account = 56 5391 0375 9387 5309
Limit = 2500
Balance = 2624.0
New Balance = 2524.0
New Balance = 2424.0
New Balance = 2324.0
New Balance = 2224.0
New Balance = 2124.0
New Balance = 2024.0
New Balance = 1924.0
New Balance = 1824.0
New Balance = 1724.0
New Balance = 1624.0
New Balance = 1524.0
New Balance = 1424.0
New Balance = 1324.0
New Balance = 1224.0
New Balance = 1124.0
New Balance = 1024.0
New Balance = 924.0
New Balance = 824.0
New Balance = 724.0
New Balance = 624.0
New Balance = 524.0
New Balance = 424.0
New Balance = 324.0
New Balance = 224.0
New Balance = 124.0
New Balance = 24.0

Customer = John Bowman


Bank = California Federal
Account = 3485 0399 3395 1954
Limit = 3500
Balance = 3675.0
New Balance = 3575.0
New Balance = 3475.0
New Balance = 3375.0
New Balance = 3275.0
New Balance = 3175.0
New Balance = 3075.0
New Balance = 2975.0
New Balance = 2875.0
New Balance = 2775.0
New Balance = 2675.0
New Balance = 2575.0
New Balance = 2475.0
New Balance = 2375.0
New Balance = 2275.0
New Balance = 2175.0
New Balance = 2075.0
New Balance = 1975.0
New Balance = 1875.0
New Balance = 1775.0
New Balance = 1675.0
New Balance = 1575.0
New Balance = 1475.0
New Balance = 1375.0
New Balance = 1275.0
New Balance = 1175.0
New Balance = 1075.0
New Balance = 975.0
New Balance = 875.0
New Balance = 775.0
New Balance = 675.0
New Balance = 575.0
New Balance = 475.0
New Balance = 375.0
New Balance = 275.0
New Balance = 175.0
New Balance = 75.0
Customer = John Bowman
Bank = California Finance
Account = 5391 0375 9387 5309
Limit = 5000
Balance = 5049.0
New Balance = 4949.0
New Balance = 4849.0
New Balance = 4749.0
New Balance = 4649.0
New Balance = 4549.0
New Balance = 4449.0
New Balance = 4349.0
New Balance = 4249.0
New Balance = 4149.0
New Balance = 4049.0
New Balance = 3949.0
New Balance = 3849.0
New Balance = 3749.0
New Balance = 3649.0
New Balance = 3549.0
New Balance = 3449.0
New Balance = 3349.0
New Balance = 3249.0
New Balance = 3149.0
New Balance = 3049.0
New Balance = 2949.0
New Balance = 2849.0
New Balance = 2749.0
New Balance = 2649.0
New Balance = 2549.0
New Balance = 2449.0
New Balance = 2349.0
New Balance = 2249.0
New Balance = 2149.0
New Balance = 2049.0
New Balance = 1949.0
New Balance = 1849.0
New Balance = 1749.0
New Balance = 1649.0
New Balance = 1549.0
New Balance = 1449.0
New Balance = 1349.0
New Balance = 1249.0
New Balance = 1149.0
New Balance = 1049.0
New Balance = 949.0
New Balance = 849.0
New Balance = 749.0
New Balance = 649.0
New Balance = 549.0
New Balance = 449.0
New Balance = 349.0
New Balance = 249.0
New Balance = 149.0
New Balance = 49.0
In [29]:
#----------C2-29---------------------
class PCCwMonthly(PredatoryCreditCard):
MINIMUM_PCT = 0.1
LATE_FEE = 10

def __init__(self, customer, bank, acnt, limit, apr):


super().__init__(customer, bank, acnt, limit, apr)
self._minimum_payment = 0

def process_month(self):
super().process_month()
if self._minimum_payment >0:
self._balance += self.LATE_FEE
if self._balance >0:
self._minimum_payment = self._balance * self.MINIMUM_PCT

def make_payment(self, value):


if super().make_payment(value):
self._minimum_payment = max (0, self._minimum_payment - value)

cc1 = PCCwMonthly('John Bowman' , 'California Savings' ,'56 5391 0375 9387


5309' , 2500, 0.15)

cc1.charge(100)
cc1.charge(200)
cc1.process_month()
print(cc1.get_balance(), cc1._minimum_payment)

cc1.process_month()
print(cc1.get_balance(), cc1._minimum_payment)
303.514475075956 30.3514475075956
317.07012193544375 31.707012193544376
In [30]:
#---------C2-30----------------------
class PredatoryCreditCard2(CreditCard):
MAX_CHARGES = 10
def __init__(self, customer, bank, acnt, limit, apr):
super().__init__(customer, bank, acnt, limit)
self._apr = apr
self._num_charges = 0

def charge(self, price):


success = super().charge(price)
if not success:
super().set_balance(super().get_balance() + 5)
else:
self._num_charges += 1
if self._num_charges > self.MAX_CHARGES:
super().set_balance(super().get_balance() + 1)

return success
def process_month(self):
if self._balance >0:
monthly_factor = pow(1+self._apr, 1/12)
super().set_balance(super().get_balance() * monthly_factor)
self._num_charges = 0 #reset the counter at the beginning of each
month

wallet = []
wallet.append(PredatoryCreditCard('John Bowman' , 'California Savings' ,'56
5391 0375 9387 5309' , 2500, 0.15))
wallet.append(PredatoryCreditCard('John Bowman' , 'California Federal'
,'3485 0399 3395 1954' , 3500, 0.15))
wallet.append(PredatoryCreditCard('John Bowman' , 'California Finance'
,'5391 0375 9387 5309' , 5000, 0.30))

for val in range (1,100):


wallet[0].charge(val)
wallet[1].charge(2*val)
wallet[2].charge(3*val)

for c in range(3):
print ('Customer = ', wallet[c].get_customer())
print ('Bank = ', wallet[c].get_bank())
print('Account = ', wallet[c].get_account())
print ('Limit = ', wallet[c].get_limit())
print('Balance = ', wallet[c].get_balance())
while wallet[c].get_balance()>100:
wallet[c].make_payment(100)
print('New Balance = ', wallet[c].get_balance())
print()

Your deposit of 171.0 exceeds your remainder of 166.0


Your deposit of 174.0 exceeds your remainder of 161.0
Your deposit of 118.0 exceeds your remainder of 30.0
Your deposit of 177.0 exceeds your remainder of 156.0
Your deposit of 120.0 exceeds your remainder of 25.0
Your deposit of 180.0 exceeds your remainder of 151.0
Your deposit of 122.0 exceeds your remainder of 20.0
Your deposit of 183.0 exceeds your remainder of 146.0
Your deposit of 124.0 exceeds your remainder of 15.0
Your deposit of 186.0 exceeds your remainder of 141.0
Your deposit of 126.0 exceeds your remainder of 10.0
Your deposit of 189.0 exceeds your remainder of 136.0
Your deposit of 128.0 exceeds your remainder of 5.0
Your deposit of 192.0 exceeds your remainder of 131.0
Your deposit of 130.0 exceeds your remainder of 0.0
Your deposit of 195.0 exceeds your remainder of 126.0
Your deposit of 132.0 exceeds your remainder of -5.0
Your deposit of 198.0 exceeds your remainder of 121.0
Your deposit of 134.0 exceeds your remainder of -10.0
Your deposit of 201.0 exceeds your remainder of 116.0
Your deposit of 136.0 exceeds your remainder of -15.0
Your deposit of 204.0 exceeds your remainder of 111.0
Your deposit of 138.0 exceeds your remainder of -20.0
Your deposit of 207.0 exceeds your remainder of 106.0
Your deposit of 70.0 exceeds your remainder of 26.0
Your deposit of 140.0 exceeds your remainder of -25.0
Your deposit of 210.0 exceeds your remainder of 101.0
Your deposit of 71.0 exceeds your remainder of 21.0
Your deposit of 142.0 exceeds your remainder of -30.0
Your deposit of 213.0 exceeds your remainder of 96.0
Your deposit of 72.0 exceeds your remainder of 16.0
Your deposit of 144.0 exceeds your remainder of -35.0
Your deposit of 216.0 exceeds your remainder of 91.0
Your deposit of 73.0 exceeds your remainder of 11.0
Your deposit of 146.0 exceeds your remainder of -40.0
Your deposit of 219.0 exceeds your remainder of 86.0
Your deposit of 74.0 exceeds your remainder of 6.0
Your deposit of 148.0 exceeds your remainder of -45.0
Your deposit of 222.0 exceeds your remainder of 81.0
Your deposit of 75.0 exceeds your remainder of 1.0
Your deposit of 150.0 exceeds your remainder of -50.0
Your deposit of 225.0 exceeds your remainder of 76.0
Your deposit of 76.0 exceeds your remainder of -4.0
Your deposit of 152.0 exceeds your remainder of -55.0
Your deposit of 228.0 exceeds your remainder of 71.0
Your deposit of 77.0 exceeds your remainder of -9.0
Your deposit of 154.0 exceeds your remainder of -60.0
Your deposit of 231.0 exceeds your remainder of 66.0
Your deposit of 78.0 exceeds your remainder of -14.0
Your deposit of 156.0 exceeds your remainder of -65.0
Your deposit of 234.0 exceeds your remainder of 61.0
Your deposit of 79.0 exceeds your remainder of -19.0
Your deposit of 158.0 exceeds your remainder of -70.0
Your deposit of 237.0 exceeds your remainder of 56.0
Your deposit of 80.0 exceeds your remainder of -24.0
Your deposit of 160.0 exceeds your remainder of -75.0
Your deposit of 240.0 exceeds your remainder of 51.0
Your deposit of 81.0 exceeds your remainder of -29.0
Your deposit of 162.0 exceeds your remainder of -80.0
Your deposit of 243.0 exceeds your remainder of 46.0
Your deposit of 82.0 exceeds your remainder of -34.0
Your deposit of 164.0 exceeds your remainder of -85.0
Your deposit of 246.0 exceeds your remainder of 41.0
Your deposit of 83.0 exceeds your remainder of -39.0
Your deposit of 166.0 exceeds your remainder of -90.0
Your deposit of 249.0 exceeds your remainder of 36.0
Your deposit of 84.0 exceeds your remainder of -44.0
Your deposit of 168.0 exceeds your remainder of -95.0
Your deposit of 252.0 exceeds your remainder of 31.0
Your deposit of 85.0 exceeds your remainder of -49.0
Your deposit of 170.0 exceeds your remainder of -100.0
Your deposit of 255.0 exceeds your remainder of 26.0
Your deposit of 86.0 exceeds your remainder of -54.0
Your deposit of 172.0 exceeds your remainder of -105.0
Your deposit of 258.0 exceeds your remainder of 21.0
Your deposit of 87.0 exceeds your remainder of -59.0
Your deposit of 174.0 exceeds your remainder of -110.0
Your deposit of 261.0 exceeds your remainder of 16.0
Your deposit of 88.0 exceeds your remainder of -64.0
Your deposit of 176.0 exceeds your remainder of -115.0
Your deposit of 264.0 exceeds your remainder of 11.0
Your deposit of 89.0 exceeds your remainder of -69.0
Your deposit of 178.0 exceeds your remainder of -120.0
Your deposit of 267.0 exceeds your remainder of 6.0
Your deposit of 90.0 exceeds your remainder of -74.0
Your deposit of 180.0 exceeds your remainder of -125.0
Your deposit of 270.0 exceeds your remainder of 1.0
Your deposit of 91.0 exceeds your remainder of -79.0
Your deposit of 182.0 exceeds your remainder of -130.0
Your deposit of 273.0 exceeds your remainder of -4.0
Your deposit of 92.0 exceeds your remainder of -84.0
Your deposit of 184.0 exceeds your remainder of -135.0
Your deposit of 276.0 exceeds your remainder of -9.0
Your deposit of 93.0 exceeds your remainder of -89.0
Your deposit of 186.0 exceeds your remainder of -140.0
Your deposit of 279.0 exceeds your remainder of -14.0
Your deposit of 94.0 exceeds your remainder of -94.0
Your deposit of 188.0 exceeds your remainder of -145.0
Your deposit of 282.0 exceeds your remainder of -19.0
Your deposit of 95.0 exceeds your remainder of -99.0
Your deposit of 190.0 exceeds your remainder of -150.0
Your deposit of 285.0 exceeds your remainder of -24.0
Your deposit of 96.0 exceeds your remainder of -104.0
Your deposit of 192.0 exceeds your remainder of -155.0
Your deposit of 288.0 exceeds your remainder of -29.0
Your deposit of 97.0 exceeds your remainder of -109.0
Your deposit of 194.0 exceeds your remainder of -160.0
Your deposit of 291.0 exceeds your remainder of -34.0
Your deposit of 98.0 exceeds your remainder of -114.0
Your deposit of 196.0 exceeds your remainder of -165.0
Your deposit of 294.0 exceeds your remainder of -39.0
Your deposit of 99.0 exceeds your remainder of -119.0
Your deposit of 198.0 exceeds your remainder of -170.0
Your deposit of 297.0 exceeds your remainder of -44.0
Customer = John Bowman
Bank = California Savings
Account = 56 5391 0375 9387 5309
Limit = 2500
Balance = 2624.0
New Balance = 2524.0
New Balance = 2424.0
New Balance = 2324.0
New Balance = 2224.0
New Balance = 2124.0
New Balance = 2024.0
New Balance = 1924.0
New Balance = 1824.0
New Balance = 1724.0
New Balance = 1624.0
New Balance = 1524.0
New Balance = 1424.0
New Balance = 1324.0
New Balance = 1224.0
New Balance = 1124.0
New Balance = 1024.0
New Balance = 924.0
New Balance = 824.0
New Balance = 724.0
New Balance = 624.0
New Balance = 524.0
New Balance = 424.0
New Balance = 324.0
New Balance = 224.0
New Balance = 124.0
New Balance = 24.0

Customer = John Bowman


Bank = California Federal
Account = 3485 0399 3395 1954
Limit = 3500
Balance = 3675.0
New Balance = 3575.0
New Balance = 3475.0
New Balance = 3375.0
New Balance = 3275.0
New Balance = 3175.0
New Balance = 3075.0
New Balance = 2975.0
New Balance = 2875.0
New Balance = 2775.0
New Balance = 2675.0
New Balance = 2575.0
New Balance = 2475.0
New Balance = 2375.0
New Balance = 2275.0
New Balance = 2175.0
New Balance = 2075.0
New Balance = 1975.0
New Balance = 1875.0
New Balance = 1775.0
New Balance = 1675.0
New Balance = 1575.0
New Balance = 1475.0
New Balance = 1375.0
New Balance = 1275.0
New Balance = 1175.0
New Balance = 1075.0
New Balance = 975.0
New Balance = 875.0
New Balance = 775.0
New Balance = 675.0
New Balance = 575.0
New Balance = 475.0
New Balance = 375.0
New Balance = 275.0
New Balance = 175.0
New Balance = 75.0

Customer = John Bowman


Bank = California Finance
Account = 5391 0375 9387 5309
Limit = 5000
Balance = 5049.0
New Balance = 4949.0
New Balance = 4849.0
New Balance = 4749.0
New Balance = 4649.0
New Balance = 4549.0
New Balance = 4449.0
New Balance = 4349.0
New Balance = 4249.0
New Balance = 4149.0
New Balance = 4049.0
New Balance = 3949.0
New Balance = 3849.0
New Balance = 3749.0
New Balance = 3649.0
New Balance = 3549.0
New Balance = 3449.0
New Balance = 3349.0
New Balance = 3249.0
New Balance = 3149.0
New Balance = 3049.0
New Balance = 2949.0
New Balance = 2849.0
New Balance = 2749.0
New Balance = 2649.0
New Balance = 2549.0
New Balance = 2449.0
New Balance = 2349.0
New Balance = 2249.0
New Balance = 2149.0
New Balance = 2049.0
New Balance = 1949.0
New Balance = 1849.0
New Balance = 1749.0
New Balance = 1649.0
New Balance = 1549.0
New Balance = 1449.0
New Balance = 1349.0
New Balance = 1249.0
New Balance = 1149.0
New Balance = 1049.0
New Balance = 949.0
New Balance = 849.0
New Balance = 749.0
New Balance = 649.0
New Balance = 549.0
New Balance = 449.0
New Balance = 349.0
New Balance = 249.0
New Balance = 149.0
New Balance = 49.0

In [31]:
#----------C-31----------------
class AbsoluteDiffProgression(Progression):
def __init__(self, first=2, second=200):
self._current = first
self._prev = 202

def __next__(self):
answer = self._current
self._current, self._prev = abs(self._current-self._prev),
self._current
return answer

p = Progression()
p.print_progression(10)

f = AbsoluteDiffProgression()
#for i in range (8):
# print (f'Value Number {i+1} is {f[i]}')
f.print_progression(8)
0 1 2 3 4 5 6 7 8 9
2 200 198 2 196 194 2 192
In [32]:
#-----------C-32------------
class SQRTProgression(Progression):
def __init__(self, start = 65536):
self._current = start

def __next__(self):
answer = self._current
self._current = self._current **0.5
return answer

def __getitem__(self, index):


return (self._current**(1/(2**index)))

p = Progression()
p.print_progression(10)

f = SQRTProgression()
for i in range (8):
print (f'Value Number {i+1} is {f[i]}')
f.print_progression(8)
0 1 2 3 4 5 6 7 8 9
Value Number 1 is 65536.0
Value Number 2 is 256.0
Value Number 3 is 16.0
Value Number 4 is 4.0
Value Number 5 is 2.0
Value Number 6 is 1.4142135623730951
Value Number 7 is 1.189207115002721
Value Number 8 is 1.0905077326652577
65536 256.0 16.0 4.0 2.0 1.4142135623730951 1.189207115002721 1.09050773266
52577

Projects
In [33]:
#------------P2-33----------------
class Polynomial():
def __init__(self, length = 3):
self._coords = [0]*length

def __len__(self):
return len(self._coords)

def __getitem__(self, index):


if index >= len(self): raise IndexError('Index out of range')

return self._coords[index]

def __repr__(self):
output_string = []
for i in range(len(self)):
output_string.append(f'{self[i]}x^{i} ')
return ''.join(output_string)

def __setitem__(self, index, value):


try:
self._coords[index] = value
except Exception as e:
print (e)

def derivative(self):
result = Polynomial(len(self)-1)
for i in range(1, len(self)):
result[i-1] = self[i]*i
return result

p = Polynomial(10)
for i in range(len(p)):
p[i] = i
print(p)

p.derivative()
0x^0 1x^1 2x^2 3x^3 4x^4 5x^5 6x^6 7x^7 8x^8 9x^9
Out[33]:
1x^0 4x^1 9x^2 16x^3 25x^4 36x^5 49x^6 64x^7 81x^8
In [35]:
#-----------P2-34--------------------
class DocumentReader():

def __init__(self, filepath):


self._filepath = filepath
self._total_characters = 0
self._charcount = self._initialize_array()

self._read_document()

def _read_document(self):
fp = open(self._filepath)
all_text = fp.read().lower()
for char in all_text:
if self._check_if_character(char):
self._charcount[ord(char)-ord('a')] += 1
self._total_characters = sum(self._charcount)

def _initialize_array(self):
return [0]*(ord('z')-ord('a')+1)

def _check_if_character(self, char):


number = ord(char)
#only need the first one since we .lower() -ed the original text.
It will short-circuit
#most of the time, so the second expression won't even be checked
if (number<=ord('z') and number>= ord('a')) or (number<=ord('Z')
and number>= ord('A')):
return True
else:
return False

def output_graph(self):
max_value = max(self._charcount)
for i in range(len(self._charcount)):
print (chr(i+ord('a')),
'X'*int(self._charcount[i]/max_value*100))

print ('Each x represents: ', max_value*100, 'instances of that


character (rounded down)')

aiw = DocumentReader(r'SampleFiles/Chapter1 ExampleText2 (Alice in


Wonderland).txt')
#aiw._charcount, aiw._total_characters
aiw.output_graph()
a XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
b XXXXXXXXXX
c XXXXXXXXXXXXXXXXX
d XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
e XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXX
f XXXXXXXXXXXXXX
g XXXXXXXXXXXXXXXXXX
h XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
i XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
j X
k XXXXXXXX
l XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
m XXXXXXXXXXXXXXX
n XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
o XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
p XXXXXXXXXXX
q X
r XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
s XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
t XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX
u XXXXXXXXXXXXXXXXXXXXXXXXX
v XXXXXX
w XXXXXXXXXXXXXXXXXXX
x X
y XXXXXXXXXXXXXXXX
z
Each x represents: 1357900 instances of that character (rounded down)
In [36]:
#------------P2-35--------------------------
import random

#Unknowns: What happens if you create a new packet without deleting the old
one?
#Auume it overwrites it

class AliceBot():
CHANCE_OF_ACTING = 0.3
def __init__(self):
self._current_packet = None

def act(self):
if random.random()<=self.CHANCE_OF_ACTING:
self._current_packet = self._create_packet()
return True
else: return False

def _create_packet(self):
length = random.randint(5,20)
packet = [' ']*length
for i in range(length):
packet[i] = chr(random.randint(ord('A'), ord('z')))
return ''.join(packet)

def get_packet(self):
return self._current_packet

def delete_packet(self):
self._current_packet = None

class InternetBot():
def __init__(self):
self._new_packet = False
self._Alice = None

def check_for_packet(self):
if self._Alice.get_packet() is not None:
return True
else:
return False

def read_packet(self):
if self._new_packet:
return self._Alice.get_packet()
else:
return None

def delete_packet(self):
self._Alice.delete_packet()

def assign_Alice(self, alice):


self._Alice = alice

class BobBot():
def check_for_packet(self, other):
if other.check_for_packet():
return True
else:
return False

def delete_packet(self, other):


other.delete_packet()

#Simulator for this process


Alice = AliceBot()
Inter = InternetBot()
Inter.assign_Alice(Alice)
Bob = BobBot()

for i in range(50):
print(f'Time is {i}')
if Alice.act(): print('Created the packet', Alice.get_packet())
if Bob.check_for_packet(Inter):
print('Bob detected the packet')
Bob.delete_packet(Inter)

Time is 0
Time is 1
Time is 2
Time is 3
Time is 4
Time is 5
Time is 6
Created the packet zHtWxN[
Bob detected the packet
Time is 7
Time is 8
Created the packet yb[HDaCvO[Hk
Bob detected the packet
Time is 9
Time is 10
Time is 11
Time is 12
Time is 13
Created the packet WNKTBnm
Bob detected the packet
Time is 14
Time is 15
Time is 16
Time is 17
Time is 18
Time is 19
Time is 20
Created the packet aji\Nzu
Bob detected the packet
Time is 21
Time is 22
Time is 23
Time is 24
Time is 25
Time is 26
Time is 27
Created the packet rWLejVe
Bob detected the packet
Time is 28
Time is 29
Time is 30
Time is 31
Created the packet lxiWlyx
Bob detected the packet
Time is 32
Created the packet bRONEGCPpKg_pzl
Bob detected the packet
Time is 33
Created the packet fbFO]Ia
Bob detected the packet
Time is 34
Time is 35
Time is 36
Time is 37
Time is 38
Time is 39
Time is 40
Time is 41
Time is 42
Created the packet gdJsrpvPSwWlHr\[
Bob detected the packet
Time is 43
Time is 44
Created the packet FYNJrLps
Bob detected the packet
Time is 45
Time is 46
Time is 47
Time is 48
Time is 49
In [37]:
#-------------------P2-36---------------------
import random
#These should be nested in theory and then accessed using self.Bear, or
self.Fish

class RiverEcosystem():

class Bear():
def __init__(self, location):
self._location = location

class Fish():
def __init__(self, location):
self._location = location

MOVE_CHANCE = 0.3
LR_CHANCE = 0.5

def __init__(self, length = 100, bears = 3, fish = 10):


self._ecosystem = [None]*length

self._bears = self.assign_object(self.Bear, bears)


self._fish = self.assign_object(self.Fish, fish)

self._time = 0

def __len__(self):
return (len(self._ecosystem))

def __getitem__(self, index):


return self._ecosystem[index]

def __setitem__(self, index, value):


self._ecosystem[index] = value

def assign_object(self, obj, number):


assigned = 0
object_list = []
maximum_attempts = 100
attempts = 0
while assigned <number and attempts < maximum_attempts:
attempts +=1
i = random.randint(0, len(self)-1)
if self[i] is None:
new_obj = obj(i)
assigned += 1
self[i] = new_obj
object_list.append(new_obj)
return object_list

def __repr__(self):
output_string = []
for element in self._ecosystem:
if element is None:
output_string += '-'
elif isinstance(element, self.Bear):
output_string += 'B'
elif isinstance(element, self.Fish):
output_string += 'F'
else:
output_string += '?'

return ''.join(output_string)

def _delete_object(self, obj, obj_list):


#Challenge is to also delete it from the list of bears/fish
target = None

for i in range(len(obj_list)):
if obj is obj_list[i]:
target = i
if target is not None: del (obj_list[target])

def _attempt_move(self, obj, target_location):


if target_location <0 or target_location >=len(self):
#print ('Move is out of bounds')
return False
elif self[target_location] is None:
self[obj._location], self[target_location] =
self[target_location], self[obj._location]
elif type(obj) == type(self[target_location]):
#if they are the same type, create one new instance of that
object
self.assign_object(type(obj), 1)
#if not the same, check who is the fish...
elif isinstance(obj, self.Fish):
self._delete_object(obj, self._fish)
elif isinstance(self[target_location], self.Fish):
self._delete_object(self[target_location], self._fish)

def determine_action(self, obj):


if random.random() < self.MOVE_CHANCE:
if random.random() <self.LR_CHANCE:
self._attempt_move(obj, obj._location -1)

else:
self._attempt_move(obj, obj._location +1)

def timestep(self):
self._time += 1
for f in self._fish:
self.determine_action(f)
for b in self._bears:
self.determine_action(b)

Game1 = RiverEcosystem(100)
print('Currently playing a game with 3 bears and 10 fish')
for _ in range(40):
print (Game1)
Game1.timestep()
print('\n\n')

Game2 = RiverEcosystem (100, 10, 10)


print ('Currently playing a game with 10 bears and 10 fish')
for _ in range(40):
print (Game2)
Game2.timestep()

Currently playing a game with 3 bears and 10 fish


--------FF--------F-------------B--FF----F-------------FB------------------
------B---F-F----------F-
-------F-F--------F------------B---FF----F-------------FB------------------
-----B----F-F----------F-
------FF-F--------F-----------FB---FF-----F------------FB------------------
-----B-----FF---------F--
F-----FF-F---------F----------FB---FF-----F----F-------FB------------------
-----B-----F-F-------BF--
F-----FF--F--------F----------FB--FF-F----F----F-------FB------B-----------
F----B-----F-F-------BF--
F-----FF--F--------F------F---FB--FF-F----F----F-------FB------B-----B-----
F----B-----F-F-------BF--
F-----FFF-F--------F-F----F---FB--FF-F----F----F-------FB------B-----B-----
F----B-----F-F----F--BF--
F-----FFF-F--------F-F----F---FB--FF-F----F----F-------F-B-----B---F-BF----
F----B-----F-F----F--BF--
F-----FF-FF--------F-F----F---FB--FF-F----F----F----F--F-B-----B---F-BF----
F----B-----F-F----F--BF--
F-----FF-FF-----F-BF-F----F---FB--F-FF----F----F--F-F--F-B-----B---F-BF----
F----B-----F-F----F--BF--
F-----FF-FF-----F-BF-F-F--F---FB--F-FF----F----F--F-F--F-B-----B---F-BF----
F----B-----F-F----F--BF--
F-----FF-FF-----FB-F-F-F--F---FB--F-FF---FF----F--F-F--F-B-----B---F-BF----
F----B-----F-F----F--BF--
F-----FF-FF-----FB-F-F-F--F---FB--F-FF---FF----F--F-F--F-BF----BF--F-BF----
F----B-----F-F----F--BF--
F-----FF-FF-----FB-F-F-F--F---FB--F-FF---FF----F--F-F--F-BF----BF--F-BF----
F----B--B--F-F----F--BF--
F-----FF-FF-----FBFF-F-F--F---FB--FF-F---FF----F--F-F--F-BF----BF--F-BF----
F----B--B--F-F----F--BF--
F-----FF-FF-----FBFFFF-F-FF---FB--FF-F---FF----F--F-F--F-BF----BF--F-BF----
F----B--B--F-F----F--BF--
F-----FF-FF-----FBFFFF-F-FF---FB--F-FF---FF----F--F-F--FBBF----BF--F-BF----
F----B--B--F-F---FF--BF--
F-----FFFFF-----FBFFFF-F-FF---FB-FF-FF--F-F----F--F-F--FBBF----BF--F-BF----
F----B--B--F-F---FF--BF--
F----FFFFFF-----FBFFFF-F-FF---FB-FF-FF--F-F----F-BF-F--FBBF----BF--F-BF-B--
F----B--B-FF-FF--FF--BF-B
F----FFFFFF---F-FBFFFF-F-FF-F-FB-FF-FF--F-F----F-BF-F-FFBBF----BF--F-BF-B--
F----B--B-FF-FF--FF--BF-B
F----FFFFFF---F-FBFFFF-F-FF-F-FB-FF-FF--F-F----F-BF-F-FFBBF----BF--F-BF-B--
F----B--B-FF-FF--FF--BF-B
F----FFFFFF---F-FBFFFF-F-FF-F-FB-FF-FF--F-F----F-BF-F-FFBBF----BF--F-BF-B-F
F----B--BF-F-FF--FF--BF-B
F----FFFFFF---F-FBFFFFBF-FF-F-FB-FF-FF--F-F----F-BF-F-FFBBF----BF--F-BF-B-F
F----B--BF-F-FF--FF--BFFB
F--F-FFFFFF---F-FBFFFFBF-FF-F-FB-FF-FF--F-F----F-BF-F-FFBBF----BF--F-BF-B-F
F----B--BF-F-FF--FFF-BFFB
F--F-FFFFFF---F-FBFFFFBF-FF-F-FB-FF-FF--F-F----F-BF-F-FFBBF----BF--F-BF-B-F
F----B--BF-F-FF--FFF-BFFB
F--F-FFFFFF---F-FBFFFFBF-FF-FFFB-FF-FF--F-F---FF-BF-F-FFBBF----BF--FFBF-B-F
F----B--BF-FBFF--FFF-BFFB
F--F-FFFFFFF--F-FBFFFFBF-FF-FFFB-FF-FF--F-F---FF-BF-F-FFBBF----BF--FFBF-B-F
F----B--BF-FBFFF-FFF-BFFB
F--F-FFFFFFF--F-FBFFFFBF-FFFFFFB-FF-FF--F-F---FFBBF-F-FFBBF----BF--FFBF-B-F
F----B--BF-FBFFF-FFF-BFFB
F-FF-FFFFFFF--F-FBFFFFBF-FFFFFFB-FF-FF--F-F---FFBBF-F-FFBBF----BF--FFBF-B-F
F---FB--BF-FBFFF-FFF-BFFB
F-FFFFFFFFFF--F-FBFFFFBF-FFFFFFB-FFFFFB-F-F-B-FFBBF-F-FFBBF----BF--FFBF-B-F
FF--FBF-BF-FBFFF-FFF-BFFB
F-FFFFFFFFFF--F-FBFFFFBF-FFFFFFB-FFFFFB-F-F-B-FFBBF-F-FFBBF----BF--FFBF-BFF
FF--FBF-BF-FBFFF-FFF-BFFB
F-FFFFFFFFFF--F-FBFFFFBF-FFFFFFBFFFFFFBFFFFFB-FFBBF-F-FFBBF----BF--FFBF-BFF
FF--FBF-BF-FBFFF-FFF-BFFB
F-FFFFFFFFFF-FF-FBFFFFBF-FFFFFFBFFFFFFBFFFFFB-FFBBF-F-FFBBF----BF--FFBFFBFF
FF--FBF-BFFFBFFF-FFF-BFFB
F-FFFFFFFFFF-FF-FBFFFFBF-FFFFFFBFFFFFFBFFFFFB-FFBBF-F-FFBBF---FBF-FFFBFFBFF
FF-BFBFFBFFFBFFF-FFF-BFFB
F-FFFFFFFFFFFFF-FBFFFFBF-FFFFFFBFFFFFFBFFFFFB-FFBBF-F-FFBBFFB-FBF-FFFBFFBFF
FF-BFBFFBFFFBFFF-FFF-BFFB
F-FFFFFFFFFFFFFFFBFFFFBF-FFFFFFBFFFFFFBFFFFFB-FFBBFFF-FFBBFFBFFBF-FFFBFFBFF
FFFBFBFFBFFFBFFF-FFFBBFFB
F-FFFFFFFFFFFFFFFBFFFFBFFFFFFFFBFFFFFFBFFFFFBFFFBBFFF-FFBBFFBFFBFBFFFBFFBFF
FFFBFBFFBFFFBFFF-FFFBBFFB
F-FFFFFFFFFFFFFFFBFFFFBFFFFFFFFBFFFFFFBFFFFFBFFFBBFFFFFFBBFFBFFBFBFFFBFFBFF
FFFBFBFFBFFFBFFFFFFFBBFFB
F-FFFFFFFFFFFFFFFBFFFFBFFFFFFFFBFFFFFFBFFFFFBFFFBBFFFFFFBBFFBFFBFBFFFBFFBFF
FFFBFBFFBFFFBFFFFFFFBBFFB
FFFFFFFFFFFFFFFFFBFFFFBFFFFFFFFBFFFFFFBFFFFFBFFFBBFFFFFFBBFFBFFBFBFFFBFFBFF
FFFBFBFFBFFFBFFFFFFFBBFFB

Currently playing a game with 10 bears and 10 fish


---------B-B---B---F---F-BF--------B-F--------B-----------F-F----------F--B
------F---F--------BB-B-F
---------B-B---B---F---F-BF--------B-F--------B-----------F-F-----------F-B
------F---F--------BB-B-F
---------B-B---B---F---FB-F------B-B--F-------B---F--------FF-----------FBB
------F--F---------BB-B-F
---------B-B---B---F---FB-F------BB---F-F-----B---F-----B--FF-----------FBB
------F--F---------BB-BBF
----------BB--B----F---FB-F------BB---F-F-----B---F-----B--FF-----------FB-
B----F---F---------BB-BBF
----------BB--B----F-BF-B-F------BB---F-F---B-B---FB----B--F-F----------FB-
B----F--BFF--------BB-BBF
----------BB--B----FBBFFB-F------BB---F-F---B--B--FB---BB--F-F----------FB-
B----F--BFF--------BB-BBF
----------B-B-B----FBBFFB-F-----FBB---F-F---B--B--FB---BB--F-F----------FB-
B-F-FF--BFFB------B-B-BBF
-----B----B-B-B--F-FBBFFB-F-----FBB---F-F---B--B--FB---BB--F-F----------FB-
B-F-FF--BFFB------BB--BBF
-----B----B-B-B--F-FBBFFB-F-----FBB---F-F---B--B--FB---BB--F-F----------FB-
B-F-FF--BFFB------BB--BBF
-----B----BFB-B--F-FBBFFB-F-----FBB---F-F---B--B--FB---BB--F-F----------FB-
B-F-FF--BFFB------BB--BBF
-----B----BFB-B--FFFBBFFB-F-----FBB---F-F---BB-B--FB---BB--F-F----------FB-
B-F-FF--BFFB------BBF-BBF
-----B----BFB-B--FFFBBFFB-F-----FBB---F-F---BB-B--FB---BB--F-F----------FB-
B-F-FF--BFFB------BBF-BBF
-----B----BFB-B-FFFFBBFFB-F-----FBB---F-F---BB-B--FBF--BB--F-F----------FB-
B-F-FF--BFFB------BBFB-BF
-----B----BFB-B-FFFFBBFFB-F-----FBB---F-F---BB-B--FBF--BB--F-F----B-----FB-
B-F-FFF-BFFB------BBFB-BF
-----B----BFB-B-FFFFBBFFB-F-----FBB---F-F---BB-B--FBF--BB--F-F----B-----FB-
B-F-FFF-BFFB------BBFB-BF
-----B----BFB-B-FFFFBBFFB-F-B---FBB--FF-FF--BB-B--FBF--BB--F-F----B-----FB-
B-F-FFF-BFFB------BBFB-BF
-----B----BFB-B-FFFFBBFFB-F-B---FBB--FF-FF--BBFB--FBF--BB--FBFBB--B-----FB-
B-F-FFF-BFFB----B-BBFB-BF
-FB--B----BFB-B-FFFFBBFFB-F-B---FBB--FF-FF--BBFB--FBF--BB--FBFBB--B-B---FB-
BFF-FFF-BFFB----B-BBFB-BF
-FB--B----BFB-B-FFFFBBFFB-F-B---FBB--FF-FFBBBBFB--FBF--BB--FBFBB--B-B---FB-
BFF-FFF-BFFBB---B-BBFB-BF
-FBB-B-B--BFB-B-FFFFBBFFB-F-B---FBB--FF-FFBBBBFB--FBF--BB--FBFBB--B-B---FB-
BFF-FFF-BFFBB---B-BBFB-BF
-FBB-B-B--BFB-B-FFFFBBFFB-F-B---FBB--FF-FFBBBBFB-BFBFF-BB--FBFBB--B-B---FB-
BFF-FFF-BFFBB---B-BBFB-BF
-FBB-B-B--BFB-B-FFFFBBFFB-F-B---FBB-F-F-FFBBBBFB-BFBFFBBB--FBFBB--B-B---FB-
BFF-FF-FBFFBB---B-BBFB-BF
-FBBBBFBF-BFB-B-FFFFBBFFB-F-B---FBB-F-F-FFBBBBFB-BFBFFBBB-BFBFBB--B-B---FB-
BFF-FF-FBFFBB---B-BBFB-BF
-FBBBBFBF-BFBFBFFFFFBBFFBFF-B---FBB-F-F-FFBBBBFB-BFBFFBBB-BFBFBB-BBBB---FB-
BFF-FF-FBFFBB---B-BBFB-BF
BFBBBBFBF-BFBFBFFFFFBBFFBFF-B---FBBBF-F-FFBBBBFB-BFBFFBBB-BFBFBBFBBBB---FB-
BFF-FF-FBFFBB---B-BBFB-BF
BFBBBBFBF-BFBFBFFFFFBBFFBFFFB---FBBBF-F-FFBBBBFB-BFBFFBBB-BFBFBBFBBBB--BFB-
BFF-FF-FBFFBB---B-BBFB-BF
BFBBBBFBF-BFBFBFFFFFBBFFBFFFB--BFBBBF-F-FFBBBBFB-BFBFFBBBBBFBFBBFBBBB-B-FB-
BFFBFF-FBFFBBB--B-BBFBBBF
BFBBBBFBF-BFBFBFFFFFBBFFBFFFBB-BFBBBF-F-FFBBBBFB-BFBFFBBBBBFBFBBFBBBB-B-FB-
BFFBFFFFBFFBBB--B-BBFBBBF
BFBBBBFBF-BFBFBFFFFFBBFFBFFFBB-BFBBBF-F-FFBBBBFBBBFBFFBBBBBFBFBBFBBBB-B-FB-
BFFBFFFFBFFBBB--BBBBFBBBF
BFBBBBFBF-BFBFBFFFFFBBFFBFFFBB-BFBBBFBF-FFBBBBFBBBFBFFBBBBBFBFBBFBBBB-B-FB-
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBF-FFBBBBFBBBFBFFBBBBBFBFBBFBBBB-BBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBF-FFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBFFFFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBFFFFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBFFFFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBFFFFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBFFFFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBFFFFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
BFBBBBFBFFBFBFBFFFFFBBFFBFFFBBFBFBBBFBFFFFBBBBFBBBFBFFBBBBBFBFBBFBBBBBBBFBB
BFFBFFFFBFFBBBFBBBBBFBBBF
In [38]:
#----------------P2-37------------------------
#Note, you must run the cell from P2-36 to get the RiverEcosystem class

class RiverEcosystem2(RiverEcosystem):
class Bear():
def __init__(self, location):
self._location = location
self._strength = random.random()
self._gender = True if random.random()>0.5 else False

class Fish():
def __init__(self, location):
self._location = location
self._strength = random.random()
self._gender = True if random.random()>0.5 else False

def _attempt_move(self, obj, target_location):


if target_location <0 or target_location >=len(self):
#print ('Move is out of bounds')
return False
elif self[target_location] is None:
self[obj._location], self[target_location] =
self[target_location], self[obj._location]

elif type(obj) == type(self[target_location]):


#if they are the same type and gender, create one new instance
of that object
if obj._gender == self[target_location]._gender:
self.assign_object(type(obj), 1)
else:
to_delete = min(obj, self[target_location], key = lambda x:
x._strength)
object_list = self._fish if isinstance(obj, self.Fish) else
self._bears
#print(f'A fight!! Of strengths {obj._strength} and
{self[target_location]._strength}, {to_delete._strength} loses')
self._delete_object(to_delete, object_list)
#if not the same, check who is the fish...
elif isinstance(obj, self.Fish):
self._delete_object(obj, self._fish)
elif isinstance(self[target_location], self.Fish):
self._delete_object(self[target_location], self._fish)

Game1 = RiverEcosystem2(100)
print('Currently playing a game with 3 bears and 10 fish')
for _ in range(40):
print (Game1)
Game1.timestep()
print('\n\n')

Game2 = RiverEcosystem2(100, 10, 10)


print ('Currently playing a game with 10 bears and 10 fish')
for _ in range(40):
print (Game2)
Game2.timestep()

b1, b2 = Game2._bears[0], Game2._bears[1]


Currently playing a game with 3 bears and 10 fish
---F--F-B-F-----F----------B------------F---------------F---------F--F-----
----FB----------F--------
---F--F--BF------F--------B-------------F---------------F---------F--F-----
----FB----------F--------
---F-F---BF------F--------B-------------F---------------F---------F---F----
----FB----------F--------
----FF---B-F-----F--------B--------------F-------------F-----------F--F----
----FB-----------F-------
-F--FF---B-F-----F--------B--------------F-------------F-----------F--F----
F---FB-------F---F-------
-F--FF---B-F-----F--------B--------------F-------------F---------F-F--F----
F---FB-------F---F-------
-F--FF---B-F-----F-F-F---FB--F-----------F-------------F---------F-F--F----
F---FB-------F---F-------
-F--FF---B-F-----F-F-F---FB--F-----------F---F-----B---F-------F-F-F--F----
F---FB-------F---F-------
-F--FF---B-F-----F-F-F---FB--F-----------F---F-----B---F-------F-F-F--F----
F---FB-------F---F-------
-F--FF---B-F-----F-F-F---FB--F-----------F---F-----B---F------FF-F-F--F----
F---FB-------F---F-------
-F--FF---B-F-----F-F-F---FB--F-----------F---F-----B---F------FF-F-F--F--F-
F---FB-------F---F-------
-F--FF---B-F-----F-FFF---FB--F-----------F---F-----B-B-F------FF-F-F--F--F-
F---FBF------F---F-------
-F-FFF---B-F-----F-FFFF--FB--F-----------F---F-----B-B-F------FF-F-F--F--F-
F--BFBF------F---F-------
-F-FFF---B-F-----F-FFFF--FB--F-----------F---F---F-B-B-F------FF-F-F--F--F-
F--BFBF----F-F---F--F----
-F-FFF---B-F-----F-FFFF--FB-FF-----------F---F---F-B-B-F------FF-F-F--F--F-
F--BFBF----F-F---F--F--B-
-F-FFF---B-F-----F-FFFF--FB-FF----------BF---F---F-B-B-F------FF-F-F--F--F-
F--BFBF----F-F---F--F--B-
-F-FFF---B-F-----F-FFFF--FB-FF----------BF---F---F-B-BFF------FF-F-F--F--F-
F--BFBF----F-F---F--F--B-
-F-FFF---B-F-----F-FFFF--FB-FF-----F----BF---F---F-B-BFF------FF-F-F--F--F-
F--BFBF----F-F---F--F--B-
-F-FFF---B-F-----F-FFFF--FB-FF-----F----BF---F--FF-B-BFF------FF-F-F--F--F-
F--BFBF----F-F---F--F--B-
-F-FFF---B-F-----F-FFFF--FB-FF-----F----BF---F--FF-B-BFF------FF-F-F-BF--F-
F--BFBF----F-F---F--F--B-
-FF-FF---B-F-----F-FFFF--FB-FF-----F----BF---F--FF-B-BFF------FF-F-F-BF--F-
F--BFBF----FFF---F--F--B-
-FF-FF---B-F-----F-FFFF--FB-FF-----F----BFF--F--FF-B-BFF------FF-F-F-BF-FF-
F--BFBF----FFF---F--F--B-
-FFBFF---B-F-----F-FFFF--FB-FF-----F----BFF--F--FF-B-BFF------FF-F-F-BF-FF-
F--BFBF----FFF---F--F-FB-
-FFBFF---B-F-----F-FFFF--FB-FF-----F----BFF--F--FF-B-BFF------FF-F-F-BF-FF-
FF-BFBF----FFF---F--FFFB-
-FFBFF---B-F-----F-FFFF--FB-FF-----F----BFF--F--FF-B-BFF------FF-F-F-BF-FF-
FF-BFBF----FFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F---B-FF--F--FF-B-BFF------FF-F-F-BF-FF-
FF-BFBF----FFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F---B-FF--F--FF-B-BFF------FF-F-F-BF-FF-
FF-BFBF----FFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF------FF-F-F-BF-FF-
FF-BFBF---BFFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF------FF-F-F-BF-FF-
FF-BFBF---BFFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF------FF-F-FB-F-FF-
FF-BFBF-F-BFFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF------FF-F-FB-F-FF-
FF-BFBF-F-BFFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF---F--FF-F-FB-F-FF-
FF-BFBF-F-BFFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF---F--FF-F-FB-F-FF-
FF-BFBF-F-BFFF---FF-FFFB-
-FFBFF---B-F-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF---F--FF-F-FB-F-FF-
FF-BFBF-F-BFFF---FF-FFFB-
BFFBFF---BBF-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF---F--FF-F-FB-F-FF-
FF-BFBF-FFBFFF---FF-FFFB-
BFFBFF---BBF-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF---F--FF-F-FB-F-FF-
FF-BFBF-FFBFFF---FF-FFFB-
BFFBFF---BBF-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF---F--FF-F-FB-F-FF-
FF-BFBF-FFBFFF---FF-FFFB-
BFFBFF---BBF-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF-F-F--FF-F-FB-F-FF-
FF-BFBF-FFBFFF---FF-FFFB-
BFFBFF---BBF-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF-F-F--FF-F-FB-F-FF-
FF-BFBF-FFBFFF---FF-FFFB-
BFFBFF---BBF-F---F-FFFF--FB-FF-----F--FB-FF--F--FF-B-BFF-FFF--FF-F-FB-F-FF-
FF-BFBF-FFBFFF---FF-FFFB-

Currently playing a game with 10 bears and 10 fish


-F-F------------B-B--FF-B--B---------------B-------F---------B--B---F-F---B
----B--F-------F--F--B---
--F-F-----------B-B--FF-B--B---------------B-------F----------B-B--F--F---B
----B--F-------F--F--B---
--F-F-----------B-B--FF-B--B--------------FB--------F---------B--B-F---F--B
----B--F-------F-F---B---
--F-F-----------BFB--FF--B--B-------------FB--------F---------B--B-F---F-FB
-----B-F--------FF---B---
--F-F-----------BFB--FFFFB--B-------------FB--------F---------B--B-F---F-FB
-----B-F----F---FF--B----
--F-F-----------BFB--FFFFB--B-------------FB--------F---------B--B-F---F-FB
---F-B-FF---F---FF--B----
--F-F----------FBFB--FFFFB--B-F-----------FB--------F-----F---B--B-F---F-FB
---F-B-FF---F---FF--B----
--F-F----------FBF-B-FFFFB--B-F--B---F----FB--------F-----F---B--B-F---F-F-
B--F-B-FF---F---FF--B----
--F-F----------FBF-BF-FFFB--B-F--B---F----FB--------F-----F---B--B-F---F-F-
B--F-B-FF---F---FF--B----
--F-F----------FBFBBF-FFFB--B-F--B---F----FB----F---F-----F---B--B-F---F-F-
B--F-B-FF---F-B-FF--B----
--F-F----------FBFBBF-FFFB--B-F--B---F----FB----F---F-----F---B--B-F---F-F-
B--F-B-FF---F-B-FF--B----
--F-F----------FBFBBF-FFFB--B-F-FB---F----F-B---F---F-----F---B--B-F---F-F-
B--F-B-FF---F-B-FF--B---B
--F-F----------FBFBBF-FFFB--B-F-FB---F----F-B---F---F-----F---B--B-F---F-F-
B--FFB-FF---F-B-FF--B---B
--F-F--------F-FBFBBF-FFFB--B-F-FBB--F----F-B---F---F-----F---B--B-F---F-F-
BB-FFB-FF---F-B-FF-BB---B
--F-F-----B--F-FBFBBF-FFFB-BB-F-FBB--F----F-B---FF--F-----F---B--B-F---F-F-
BB-FFB-FF---F-B-FF-BB---B
F-F-F-----B--F-FBFBBFBFFFB-BBBF-FBBB-F-F--F-B---FF--F-----F---B--B-F---F-F-
BB-FFB-FF---F-B-FF-BB---B
F-F-F-----B--F-FBFBBFBFFFB-BBBF-FBBB-F-F--F-B---FF--F-----F---B--B-F---F-F-
BB-FFB-FF---F-B-FF-BB---B
F-F-F-----B--F-FBFBBFBFFFBB-BBF-FBBB-F-F--F-B---FF--FB----F---B--B-F---F-F-
BB-FFB-FF---F-B-FF-BB---B
F-F-F-----BB-F-FBFBBFBFFFBB-BBF-FBBB-F-FF-F-B---FF-FFB----F---B--B-F---F-F-
BB-FFB-FF---F-BFFF-BB---B
F-F-F----FBB-F-FBFBBFBFFFBB-BBF-FBBB-F-FF-F-B---FF-FFB--B-FB--B--B-F---F-F-
BB-FFBBFF---F-BFFF-BB---B
F-F-F----FBB-F-FBFBBFBFFFBB-BBF-FBBB-F-FF-F-B---FF-FFB--B-FBF-B--B-F---F-F-
BB-FFBBFF---F-BFFF-BB-F-B
F-F-F-B--FBB-F-FBFBBFBFFFBBFBBF-FBBB-F-FF-F-B---FF-FFB--B-FBF-B--B-F---F-F-
BB-FFBBFF---F-BFFF-BB-F-B
F-F-F-B--FBB-F-FBFBBFBFFFBBFBBF-FBBB-F-FF-F-B---FF-FFB--B-FBF-B--BFF---F-F-
BB-FFBBFF---F-BFFF-BB-F-B
F-F-F-B--FBB-F-FBFBBFBFFFBBFBBF-FBBB-F-FF-F-B---FFBFFB--B-FBF-B--BFF---F-F-
BB-FFBBFFB--F-BFFF-BB-F-B
F-F-F-B--FBB-F-FBFBBFBFFFBBFBBF-FBBB-F-FF-F-B---FFBFFB--B-FBF-B--BFFB--F-F-
BB-FFBBFFB--F-BFFF-BB-F-B
F-F-F-B-BFBB-F-FBFBBFBFFFBBFBBF-FBBBBF-FF-F-B---FFBFFB--B-FBF-B--BFFB--F-F-
BB-FFBBFFB--F-BFFF-BB-F-B
F-FFF-B-BFBB-F-FBFBBFBFFFBBFBBF-FBBBBF-FF-F-B---FFBFFB-BB-FBF-B--BFFB--F-F-
BBFFFBBFFB--F-BFFF-BB-F-B
F-FFF-B-BFBB-F-FBFBBFBFFFBBFBBFFFBBBBF-FF-F-B---FFBFFB-BB-FBF-B--BFFB--F-F-
BBFFFBBFFB--F-BFFFFBBFF-B
F-FFF-BFBFBB-F-FBFBBFBFFFBBFBBFFFBBBBF-FF-F-BB-BFFBFFB-BB-FBF-B--BFFB--F-F-
BBFFFBBFFB--F-BFFFFBBFF-B
F-FFF-BFBFBB-F-FBFBBFBFFFBBFBBFFFBBBBF-FF-F-BB-BFFBFFB-BB-FBF-B--BFFBBBF-F-
BBFFFBBFFB--F-BFFFFBBFF-B
FBFFFBBFBFBB-F-FBFBBFBFFFBBFBBFFFBBBBF-FF-F-BB-BFFBFFB-BB-FBF-B--BFFBBBFFF-
BBFFFBBFFB--F-BFFFFBBFF-B
FBFFFBBFBFBB-F-FBFBBFBFFFBBFBBFFFBBBBF-FF-F-BB-BFFBFFB-BB-FBF-B--BFFBBBFFF-
BBFFFBBFFB--F-BFFFFBBFF-B
FBFFFBBFBFBB-FFFBFBBFBFFFBBFBBFFFBBBBF-FF-F-BB-BFFBFFB-BB-FBF-BB-BFFBBBFFFF
BBFFFBBFFBB-F-BFFFFBBFF-B
FBFFFBBFBFBB-FFFBFBBFBFFFBBFBBFFFBBBBF-FF-F-BB-BFFBFFB-BB-FBF-BBBBFFBBBFFFF
BBFFFBBFFBB-F-BFFFFBBFF-B
FBFFFBBFBFBB-FFFBFBBFBFFFBBFBBFFFBBBBF-FF-FBBB-BFFBFFBBBB-FBF-BBBBFFBBBFFFF
BBFFFBBFFBB-FBBFFFFBBFF-B
FBFFFBBFBFBB-FFFBFBBFBFFFBBFBBFFFBBBBF-FF-FBBBBBFFBFFBBBB-FBFBBBBBFFBBBFFFF
BBFFFBBFFBB-FBBFFFFBBFF-B
FBFFFBBFBFBB-FFFBFBBFBFFFBBFBBFFFBBBBF-FF-FBBBBBFFBFFBBBB-FBFBBBBBFFBBBFFFF
BBFFFBBFFBB-FBBFFFFBBFF-B
FBFFFBBFBFBB-FFFBFBBFBFFFBBFBBFFFBBBBF-FF-FBBBBBFFBFFBBBB-FBFBBBBBFFBBBFFFF
BBFFFBBFFBB-FBBFFFFBBFF-B
FBFFFBBFBFBBFFFFBFBBFBFFFBBFBBFFFBBBBF-FF-FBBBBBFFBFFBBBB-FBFBBBBBFFBBBFFFF
BBFFFBBFFBBBFBBFFFFBBFF-B
FBFFFBBFBFBBFFFFBFBBFBFFFBBFBBFFFBBBBFFFF-FBBBBBFFBFFBBBB-FBFBBBBBFFBBBFFFF
BBFFFBBFFBBBFBBFFFFBBFF-B
In [40]:
#----------------P2-38-------------------------
import random
from pathlib import Path
from IPython.display import clear_output

"""
Areas for improvement:
- Page select
- Improve the flow between the book class and the main program

"""

class EbookReader():
class Book():
MIN_PRICE = 2
MAX_PRICE = 20
LINES_PER_PAGE = 15
def __init__(self, filepath):
self._name = str(filepath.name).replace('.txt', '')
self._filepath = filepath
self._price = random.random()*(self.MAX_PRICE-self.MIN_PRICE) +
self.MIN_PRICE
self._purchased = False
self._current_position = 0
self._iostream = open(self._filepath, encoding = 'latin-1')
self._length = self.determine_length()

def __repr__(self):
return(f'Book: {self._name}, Price: {self._price}, Purchased:
{self._purchased}')

def purchase_book(self):
self._purchased = True

def open_book(self):
if self._purchased:
return open(self._filepath)
else:
print('Please purchase this book first!')
return None

def seek_path(self, page=0):


self._iostream.seek(0)
num_lines = page*self.LINES_PER_PAGE
for _ in range(num_lines):
self._iostream.readline()

def read_book(self, page = None):


if not self._purchased:
print('Please purchase this book first!')
return False
else:
start = self._current_position if page is None else page
print(start)
fp = self._iostream
self.seek_path(start)
for _ in range(self.LINES_PER_PAGE):
print(fp.readline())

self._current_position = start + 1
return True

def __len__(self):
return self._length

def __getitem__(self, value):


#Choose this order to shortcircuit in the event that it is not
an int
if isinstance(value, int) and value < len(self) and value>0:
self.read_book(value)
else:
print('Invalid input')

def determine_length(self):
self._iostream.seek(0)
lines = self._iostream.readlines()
return len(lines)

def __init__(self, book_dir = 'SampleFiles/Chapter 2 Books'):


self._book_dir = Path(book_dir)
self._library = self._build_book_dictionary()
self._balance = 0
self._currentbook = None
self._statusmessage = 'Nothing to report...'

def load_money(self, value):


try:
self._balance += float(value)
return True
except Exception as e:
self.out(f'Invalid input: {e}')
return False

def out(self, message):


self._statusmessage = message

def purchase_book(self, bookname):


if bookname in self._library:
book = self._library[bookname]
if book._purchased:
self.out('You have already purchased this book')
return False
elif self._balance >= book._price:
book.purchase_book()
self._balance -= book._price
return True
else:
self.out('You have insufficient funds for that purchase')
return False

else:
self.out('Book not in library')
return False

def read_book(self, bookname, page = None):


#Need to add more error handling here...
if bookname in self._library:
self._library[bookname].read_book(page = page)
self._currentbook = self._library[bookname]
return True
else:
self.out('Book not found')
return False

def _read_page(self, book, page = None):


book.read_book(page = page)
return True

def _build_book_dictionary(self):
#create a list of all the books
booklist = {str(x.name).replace('.txt', ''):self.Book(x) for x in
self._book_dir.iterdir() if str(x).endswith('.txt')}
return booklist

def _print_catalog(self):
print("The following books are available for purchase:")
for book in self._library.values():
if not book._purchased: print(book)

def _print_owned(self):
print('You have purchased the following books:')
for book in self._library.values():
if book._purchased: print(book)

def _print_balance(self):
print('\nYour current balance is: ', self._balance)

def __repr__(self):
#clear_output()
print('Current message is:', self._statusmessage, '\n')
self._print_owned()
print('')
self._print_catalog()
self._print_balance()

print('Your current book is:', self._currentbook)


return('') #Note: a call to print expects a returned string

def console(self):
clear_output()
self._read_page(self._currentbook)

print(self)
print('Commands are: Purchase, Open, Next (for the next page)')
input_results = self.get_input()
return input_results

def get_input(self):
input_string = input()

if input_string == 'exit':
return False

elif input_string.lower() == 'purchase':


input_purchase = input('Which book would you like to purchase')
self.purchase_book(input_purchase)
return True #purchase a new book if you can

elif input_string == 'next':


#self.current_book
return True #read the next page of the book

elif input_string == 'open':


input_book = input('Which book would you like to open')

self._currentbook = input_book
#open a new book (position of the old one is still saved)
return True

else:
self.out('Invalid input')
return True
eb1 = EbookReader()
eb1.load_money(1000)
eb1.purchase_book('Alice in Wonderland')
eb1.purchase_book('Frankenstein')
print(eb1)

eb1.read_book('Alice in Wonderland')
for _ in range(10):
eb1.read_book('Alice in Wonderland')

eb1.read_book ('Alice in Wonderland', 500)


eb1._library['Alice in Wonderland'][20]
eb1._library['Alice in Wonderland']['ollo']
Current message is: Nothing to report...

You have purchased the following books:


Book: Alice in Wonderland, Price: 5.58152522697133, Purchased: True
Book: Frankenstein, Price: 16.487673424236796, Purchased: True

The following books are available for purchase:


Book: Dracula, Price: 10.998548906384219, Purchased: False
Book: Pride and Prejudice, Price: 2.150794896709954, Purchased: False
Book: Ulysses, Price: 8.096320531960483, Purchased: False

Your current balance is: 977.9308013487919


Your current book is: None

0
Project Gutenberg’s Alice’s Adventures in Wonderland, by Lewis Carro
ll

This eBook is for the use of anyone anywhere at no cost and with

almost no restrictions whatsoever. You may copy it, give it away or

re-use it under the terms of the Project Gutenberg License included

with this eBook or online at www.gutenberg.org

Title: Alice’s Adventures in Wonderland

Author: Lewis Carroll

Posting Date: June 25, 2008 [EBook #11]

Release Date: March, 1994


Last Updated: October 6, 2016

Language: English

Character set encoding: UTF-8

*** START OF THIS PROJECT GUTENBERG EBOOK ALICE’S ADVENTURES IN WONDERLAN


D ***

ALICE’S ADVENTURES IN WONDERLAND

Lewis Carroll

THE MILLENNIUM FULCRUM EDITION 3.0

CHAPTER I. Down the Rabbit-Hole


Alice was beginning to get very tired of sitting by her sister on the

bank, and of having nothing to do: once or twice she had peeped into the

book her sister was reading, but it had no pictures or conversations in

3
it, ‘and what is the use of a book,’ thought Alice ‘without pictures
or

conversations?’

So she was considering in her own mind (as well as she could, for the

hot day made her feel very sleepy and stupid), whether the pleasure

of making a daisy-chain would be worth the trouble of getting up and

picking the daisies, when suddenly a White Rabbit with pink eyes ran

close by her.

There was nothing so VERY remarkable in that; nor did Alice think it so

VERY much out of the way to hear the Rabbit say to itself, ‘Oh dear!

Oh dear! I shall be late!’ (when she thought it over afterwards, it

occurred to her that she ought to have wondered at this, but at the time

it all seemed quite natural); but when the Rabbit actually TOOK A WATCH

OUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,

4
Alice started to her feet, for it flashed across her mind that she had

never before seen a rabbit with either a waistcoat-pocket, or a watch

to take out of it, and burning with curiosity, she ran across the field

after it, and fortunately was just in time to see it pop down a large

rabbit-hole under the hedge.

In another moment down went Alice after it, never once considering how

in the world she was to get out again.


The rabbit-hole went straight on like a tunnel for some way, and then

dipped suddenly down, so suddenly that Alice had not a moment to think

about stopping herself before she found herself falling down a very deep

well.

Either the well was very deep, or she fell very slowly, for she had

5
plenty of time as she went down to look about her and to wonder what was

going to happen next. First, she tried to look down and make out what

she was coming to, but it was too dark to see anything; then she

looked at the sides of the well, and noticed that they were filled with

cupboards and book-shelves; here and there she saw maps and pictures

hung upon pegs. She took down a jar from one of the shelves as

she passed; it was labelled ‘ORANGE MARMALADE’, but to her great

disappointment it was empty: she did not like to drop the jar for fear

of killing somebody, so managed to put it into one of the cupboards as

she fell past it.

‘Well!’ thought Alice to herself, ‘after such a fall as this, I shall

think nothing of tumbling down stairs! How brave they’ll all think me at

home! Why, I wouldn’t say anything about it, even if I fell off the top

of the house!’ (Which was very likely true.)

Down, down, down. Would the fall NEVER come to an end! ‘I wonder how

many miles I’ve fallen by this time?’ she said aloud. ‘I must be gett
ing

somewhere near the centre of the earth. Let me see: that would be four

thousand miles down, I think--’ (for, you see, Alice had learnt several
things of this sort in her lessons in the schoolroom, and though this

was not a VERY good opportunity for showing off her knowledge, as there

was no one to listen to her, still it was good practice to say it over)

‘--yes, that’s about the right distance--but then I wonder what Latitud
e

or Longitude I’ve got to?’ (Alice had no idea what Latitude was, or

Longitude either, but thought they were nice grand words to say.)

Presently she began again. ‘I wonder if I shall fall right THROUGH the

earth! How funny it’ll seem to come out among the people that walk with

their heads downward! The Antipathies, I think--’ (she was rather glad

7
there WAS no one listening, this time, as it didn’t sound at all the

right word) ‘--but I shall have to ask them what the name of the country

is, you know. Please, Ma’am, is this New Zealand or Australia?’ (and

she tried to curtsey as she spoke--fancy CURTSEYING as you’re falling

through the air! Do you think you could manage it?) ‘And what an

ignorant little girl she’ll think me for asking! No, it’ll never do to

ask: perhaps I shall see it written up somewhere.’

Down, down, down. There was nothing else to do, so Alice soon began

talking again. ‘Dinah’ll miss me very much to-night, I should think!’

(Dinah was the cat.) ‘I hope they’ll remember her saucer of milk at

tea-time. Dinah my dear! I wish you were down here with me! There are no

mice in the air, I’m afraid, but you might catch a bat, and that’s very

like a mouse, you know. But do cats eat bats, I wonder?’ And here Alice

began to get rather sleepy, and went on saying to herself, in a dreamy

8
sort of way, ‘Do cats eat bats? Do cats eat bats?’ and sometimes, ‘Do

bats eat cats?’ for, you see, as she couldn’t answer either question,
it didn’t much matter which way she put it. She felt that she was dozing

off, and had just begun to dream that she was walking hand in hand with

Dinah, and saying to her very earnestly, ‘Now, Dinah, tell me the truth:

did you ever eat a bat?’ when suddenly, thump! thump! down she came upon

a heap of sticks and dry leaves, and the fall was over.

Alice was not a bit hurt, and she jumped up on to her feet in a moment:

she looked up, but it was all dark overhead; before her was another

long passage, and the White Rabbit was still in sight, hurrying down it.

There was not a moment to be lost: away went Alice like the wind, and

was just in time to hear it say, as it turned a corner, ‘Oh my ears

and whiskers, how late it’s getting!’ She was close behind it when she

turned the corner, but the Rabbit was no longer to be seen: she found

9
herself in a long, low hall, which was lit up by a row of lamps hanging

from the roof.

There were doors all round the hall, but they were all locked; and when

Alice had been all the way down one side and up the other, trying every

door, she walked sadly down the middle, wondering how she was ever to

get out again.

Suddenly she came upon a little three-legged table, all made of solid

glass; there was nothing on it except a tiny golden key, and Alice’s

first thought was that it might belong to one of the doors of the hall;

but, alas! either the locks were too large, or the key was too small,

but at any rate it would not open any of them. However, on the second

time round, she came upon a low curtain she had not noticed before, and

behind it was a little door about fifteen inches high: she tried the
10
little golden key in the lock, and to her great delight it fitted!

Alice opened the door and found that it led into a small passage, not

much larger than a rat-hole: she knelt down and looked along the passage

into the loveliest garden you ever saw. How she longed to get out of

that dark hall, and wander about among those beds of bright flowers and

those cool fountains, but she could not even get her head through the

doorway; ‘and even if my head would go through,’ thought poor Alice, â€


˜it

would be of very little use without my shoulders. Oh, how I wish I could

shut up like a telescope! I think I could, if I only knew how to begin.’

For, you see, so many out-of-the-way things had happened lately,

that Alice had begun to think that very few things indeed were really

impossible.

There seemed to be no use in waiting by the little door, so she went

500

20

Alice took up the fan and gloves, and, as the hall was very hot, she

kept fanning herself all the time she went on talking: ‘Dear, dear! How

queer everything is to-day! And yesterday things went on just as usual.


I wonder if I’ve been changed in the night? Let me think: was I the

same when I got up this morning? I almost think I can remember feeling a

little different. But if I’m not the same, the next question is, Who

in the world am I? Ah, THAT’S the great puzzle!’ And she began thinking

over all the children she knew that were of the same age as herself, to

see if she could have been changed for any of them.

‘I’m sure I’m not Ada,’ she said, ‘for her hair goes in such long

ringlets, and mine doesn’t go in ringlets at all; and I’m sure I can’
t

be Mabel, for I know all sorts of things, and she, oh! she knows such a

very little! Besides, SHE’S she, and I’m I, and--oh dear, how puzzling

Invalid input
In [41]:
"""Run this cell for console mode"""
#continue_program = True
#while continue_program:
# try:
# continue_program = eb1.console()
# except:
# continue_program = False
Out[41]:
'Run this cell for console mode'
In [42]:
#---------------------R2-39------------------------
"""Note, this wasn't as fleshed out as the other answers since the final
objective wasn't as clear/interesting"""

from abc import abstractmethod, ABCMeta


import math

class Polygon(metaclass = ABCMeta):


def __init__(self, side_lengths = [1,1,1], num_sides = 3):
self._side_lengths = side_lengths
self._num_sizes = 3

@abstractmethod
def area(self):
pass

@abstractmethod
def perimeter(self):
pass

def __repr__(self):
return (str(self._side_lengths))

class Triangle(Polygon):
def __init__(self, side_lengths):
super().__init__(side_lengths, 3)
self._perimeter = self.perimeter()
self._area = self.area()

def perimeter(self):
return(sum(self._side_lengths))

def area(self):
s = self._perimeter/2
product = s
for i in self._side_lengths:
product*=(s-i)
return product**0.5

class EquilateralTriangle(Triangle):
def __init__(self, length):
super().__init__([length]*3)

t1 = Triangle([1,2,2])
print(t1.perimeter(), t1.area())

t2 = EquilateralTriangle(3)
print(t2.perimeter(), t2.area())
print(t2)
5 0.9682458365518543
9 3.897114317029974
[3, 3, 3]
End of Chapter 2!

You might also like