Chapter 2 Exercises
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 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
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())
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
if amount < 0:
raise ValueError('Cannot make negative payments. Try the
charge method')
else:
self._balance -= amount
return True
-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
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
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 __str__(self):
return '<' + str(self._coords)[1:-1] + '>'
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
"""
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
for i in range(item+1):
answer = next(self)
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
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
"""
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
@abstractmethod
def __getitem__(self, index):
pass
In [23]:
#-----------R2-23------------
@abstractmethod
def __getitem__(self, index):
pass
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])
self._start = start
self._step = step
def __len__(self):
return self._length
r = Range(1,100,2)
print (len(r), r[3], 4 in r, 5 in r)
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
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 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()
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
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
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 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()
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
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)
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 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():
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 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))
#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()
class BobBot():
def check_for_packet(self, other):
if other.check_for_packet():
return True
else:
return False
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
self._time = 0
def __len__(self):
return (len(self._ecosystem))
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)
for i in range(len(obj_list)):
if obj is obj_list[i]:
target = i
if target is not None: del (obj_list[target])
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')
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
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')
"""
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
self._current_position = start + 1
return True
def __len__(self):
return self._length
def determine_length(self):
self._iostream.seek(0)
lines = self._iostream.readlines()
return len(lines)
else:
self.out('Book not in library')
return False
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()
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
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')
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
Language: English
Lewis Carroll
bank, and of having nothing to do: once or twice she had peeped into the
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
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!
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
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
In another moment down went Alice after it, never once considering how
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
disappointment it was empty: she did not like to drop the jar for fear
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
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
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
Down, down, down. There was nothing else to do, so Alice soon began
(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
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
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
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
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
would be of very little use without my shoulders. Oh, how I wish I could
that Alice had begun to think that very few things indeed were really
impossible.
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
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
‘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"""
@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!