Code :
def __init__(self, name, account_number, initial_amount):
self._name = name
self._no = account_number
self._balance = initial_amount
self._transactions = 0
def deposit(self, amount):
self._balance += amount
self._transactions += 1
def withdraw(self, amount):
self._balance -= amount
self._transactions += 1
def get_balance(self):
return self._balance
def dump(self):
s = '%s, %s, balance: %s, transactions: %d' % \
(self._name, self._no, self._balance, self._transactions)
print s
a1 = Account2('SHIVA', '19371554951', 20000)
a1.deposit(1000)
a1.withdraw(4000)
a1.withdraw(3500)
a1.dump()
a1.deposit(151247)
a1.dump()
Console:
SHIVA, 19371554951, balance: 13500, transactions: 3
SHIVA, 19371554951, balance: 164747, transactions: 4
Exercise 7.3
from math import sqrt
class Rectangle:
def __init__(self, x0, y0, W, H):
self.x0 = x0
self.y0 = y0
self.W = W
self.H = H
def area(self):
return self.W * self.H
def circumference(self):
return 2 * self.W + 2 * self.H
class Triangle:
def __init__(self, v1, v2, v3):
self.v1 = v1
self.v2 = v2
self.v3 = v3
def area(self):
x1, y1 = self.v1
x2, y2 = self.v2
x3, y3 = self.v3
return 0.5 * abs(x2*y3 - x3*y2 - x1*y3 + x3*y1 + x1*y1 - x2*y1)
def circumference(self):
vertices = (self.v1, self.v2, self.v3)
circumference = 0
for i in range(3):
dx = vertices[i][0] - vertices[(i-1) % 3][0]
dy = vertices[i][1] - vertices[(i-1) % 3][1]
circumference += sqrt(dx**2 + dy**2)
return circumference
rect = Rectangle(1, 0, 4, 3)
print 'Rectangle of dimensions %g x %g, and bottom left corner at (%g, %g). \
\nArea: %g\nCircumference: %g\n' \
% (rect.W, rect.H, rect. W, rect.H, rect.area(), rect.circumference())
tri = Triangle((0, 0), (3, 0), (3, 4))
print 'Triangle with vertices at %s, %s and %s.\
\nArea: %g\nCircumference: %g' \
% (tri.v1, tri.v2, tri.v3, tri.area(), tri.circumference())
CONSOLE
Rectangle of dimensions 4 x 3, and bottom left corner at (4, 3).
Area: 12
Circumference: 14
Triangle with vertices at (0, 0), (3, 0) and (3, 4).
Area: 6
Circumference: 12
Exercise 7.4
class Line:
def __init__(self, p1, p2):
x1, y1 = p1
x2, y2 = p2
self.m = float(y2 - y1)/(x2 - x1)
self.c = float(x2*y1 - x1*y2)/(x2 - x1)
def value(self, x):
return self.m*x + self.c
line = Line((0, -1), (2, 4))
print line.value(0.5), line.value(0), line.value(1)
Console :
0.25 -1.0 1.5
Exercise 7.5
class Line2:
def __init__(self, p1, p2):
if isinstance(p1, (tuple, list)) and isinstance(p2, (tuple, list)):
# p1 and p2 are both points
x1, y1 = p1
x2, y2 = p2
self.c = float(x2 * y1 - x1 * y2) / (x2 - x1)
self.m = float(y2 - y1) / (x2 - x1)
elif isinstance(p1, (tuple, list)) and isinstance(p2, (float, int)):
# p1 is a point and p2 is slope
x1, y1 = p1
self.c = y1 - p2 * x1
self.m = p2
elif isinstance(p1, (float, int)) and isinstance(p2, (float, int)):
# p1 is y-intercept and p2 is slope
self.c = p1
self.m = p2
def value(self, x):
return self.m * x + self.c
print '2 points: Line2((0, -1), (2, 4))'
lineA = Line2((0, -1), (2, 4))
print lineA.value(0.5), lineA.value(0), lineA.value(1)
print '\nA point and a slope: Line2((0, -1), 2.5)'
lineB = Line2((0, -1), 2.5)
print lineA.value(0.5), lineA.value(0), lineA.value(1)
print '\nA y-intercept and a slope: Line2(-1, 2.5)'
lineC = Line2(-1, 2.5)
print lineA.value(0.5), lineA.value(0), lineA.value(1)
Console :
2 points: Line2((0, -1), (2, 4))
0.25 -1.0 1.5
A point and a slope: Line2((0, -1), 2.5)
0.25 -1.0 1.5
A y-intercept and a slope: Line2(-1, 2.5)
0.25 -1.0 1.5
Exercise 7.6
Code :
from numpy import linspace
from cmath import sqrt
class Quadratic:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def value(self, x):
a, b, c = self.a, self.b, self.c
return a * x ** 2 + b * x + c
def table(self, L, R, n=10):
xlist = linspace(L, R, n)
print 'y = ax^2 + bx + c'
print 'a = %g, b = %g, c = %g' % (self.a, self.b, self.c)
print '-' * 30
print '%12s %12s' % ('x', 'y')
print '-' * 30
for x in xlist:
print '%12g %12g' % (x, self.value(x))
def roots(self):
a, b, c = self.a, self.b, self.c
d = sqrt(b * b - 4 * a * c)
r1 = (-b + d) / (2 * a)
r2 = (-b - d) / (2 * a)
return r1, r2
quad = Quadratic(2, -6, 12)
print quad.value(0)
print quad.value(5)
print quad.roots()
quad.table(-5, 5, 11)
console:
12
32
((1.5+1.9364916731037085j), (1.5-1.9364916731037085j))
y = ax^2 + bx + c
a = 2, b = -6, c = 12
------------------------------
x y
------------------------------
-5 92
-4 68
-3 48
-2 32
-1 20
0 12
1 8
2 8
3 12
4 20
5 32
Exercise 7.28
class Polynomial:
def __init__(self, coefficients):
self.coeff = coefficients
def __call__(self, x):
"""Evaluate the polynomial."""
s = 0
for k in self.coeff:
s += self.coeff[k] * x ** k
return s
def __add__(self, other):
result_coeff = self.coeff.copy()
for k in other.coeff:
result_coeff[k] = result_coeff.get(k, 0) + other.coeff[k]
# strip out zero coefficients
result_coeff = {k: c for k, c in result_coeff.items() if c != 0}
return Polynomial(result_coeff)
def __sub__(self, other):
result_coeff = self.coeff.copy()
for k in other.coeff:
result_coeff[k] = result_coeff.get(k, 0) - other.coeff[k]
# strip out zero coefficients
result_coeff = {k: c for k, c in result_coeff.items() if c != 0}
return Polynomial(result_coeff)
def differentiate(self):
"""Differentiate this polynomial in-place."""
d_coeff = {}
for k in self.coeff:
d_coeff[k - 1] = k * self.coeff[k]
# strip out zero coefficients
self.coeff = {k: c for k, c in d_coeff.items() if c != 0}
def derivative(self):
"""Copy this polynomial and return its derivative."""
dpdx = Polynomial(self.coeff.copy()) # make a copy
dpdx.differentiate()
return dpdx
def __str__(self):
s = ''
for k in self.coeff:
s += ' + %g*x^%d' % (self.coeff[k], k)
# Fix layout
s = s.replace('+ -', '- ')
s = s.replace('x^0', '1')
s = s.replace(' 1*', ' ')
s = s.replace('x^1 ', 'x ')
# s = s.replace('x^1', 'x') # will replace x^100 by x^00
if s[0:3] == ' + ': # remove initial +
s = s[3:]
if s[0:3] == ' - ': # fix spaces for initial -
s = '-' + s[3:]
return s
def simplestr(self):
s = ''
for k in self.coeff:
s += ' + %g*x^%d' % (self.coeff[k], k)
return s
def _test():
p1 = Polynomial({1: 1, 100: -3})
p2 = Polynomial({1: -1, 20: 1, 100: 4})
p3 = p1 + p2
print p1, ' + ', p2, ' = ', p3
p5 = p2.derivative()
print 'd/dx', p2, ' = ', p5
print 'd/dx', p2,
p2.differentiate()
print ' = ', p5
p4 = p2.derivative()
print 'd/dx', p2, ' = ', p4
p4.simplestr()
if __name__ == '__main__':
_test()
Console :
x - 3*x^100 + -x + x^20 + 4*x^100 = x^20 + x^100
d/dx -x + x^20 + 4*x^100 = -1 + 20*x^19 + 400*x^99
d/dx -x + x^20 + 4*x^100 = -1 + 20*x^19 + 400*x^99
d/dx -1 + 20*x^19 + 400*x^99 = 39600*x^98 + 380*x^18
Exercise 7.29
class Polynomial:
def __init__(self, coefficients):
self.coeff = coefficients
def __call__(self, x):
"""Evaluate the polynomial."""
s = 0
for k in self.coeff:
s += self.coeff[k] * x ** k
return s
def __add__(self, other):
result_coeff = self.coeff.copy()
for k in other.coeff:
result_coeff[k] = result_coeff.get(k, 0) + other.coeff[k]
# strip out zero coefficients
result_coeff = {k: c for k, c in result_coeff.items() if c != 0}
return Polynomial(result_coeff)
def __sub__(self, other):
result_coeff = self.coeff.copy()
for k in other.coeff:
result_coeff[k] = result_coeff.get(k, 0) - other.coeff[k]
# strip out zero coefficients
result_coeff = {k: c for k, c in result_coeff.items() if c != 0}
return Polynomial(result_coeff)
def __mul__(self, other):
c = self.coeff
d = other.coeff
result_coeff = {}
for i in c:
for j in d:
result_coeff[i + j] = result_coeff.get(i+j, 0) + c[i]*d[j]
return Polynomial(result_coeff)
def differentiate(self):
"""Differentiate this polynomial in-place."""
d_coeff = {}
for k in self.coeff:
d_coeff[k - 1] = k * self.coeff[k]
# strip out zero coefficients
self.coeff = {k: c for k, c in d_coeff.items() if c != 0}
def derivative(self):
"""Copy this polynomial and return its derivative."""
dpdx = Polynomial(self.coeff.copy()) # make a copy
dpdx.differentiate()
return dpdx
def __str__(self):
s = ''
for k in self.coeff:
s += ' + %g*x^%d' % (self.coeff[k], k)
# Fix layout
s = s.replace('+ -', '- ')
s = s.replace('x^0', '1')
s = s.replace(' 1*', ' ')
s = s.replace('x^1 ', 'x ')
# s = s.replace('x^1', 'x') # will replace x^100 by x^00
if s[0:3] == ' + ': # remove initial +
s = s[3:]
if s[0:3] == ' - ': # fix spaces for initial -
s = '-' + s[3:]
return s
def simplestr(self):
s = ''
for k in self.coeff:
s += ' + %g*x^%d' % (self.coeff[k], k)
return s
def _test():
p1 = Polynomial({1: 1, 100: -3})
p2 = Polynomial({1: -1, 20: 1, 100: 4})
p3 = p1 + p2
print p1, ' + ', p2, ' = ', p3
p4 = p1 * p2
print p1, ' * ', p2, ' = ', p4
p5 = p2.derivative()
print 'd/dx', p2, ' = ', p5
print 'd/dx', p2,
p2.differentiate()
print ' = ', p5
p4 = p2.derivative()
print 'd/dx', p2, ' = ', p4
p4.simplestr()
if __name__ == '__main__':
_test()
Console :
x - 3*x^100 + -x + x^20 + 4*x^100 = x^20 + x^100
x - 3*x^100 * -x + x^20 + 4*x^100 = -3*x^120 - 12*x^200 - x^2 + x^21 + 7*x^101
d/dx -x + x^20 + 4*x^100 = -1 + 20*x^19 + 400*x^99
d/dx -x + x^20 + 4*x^100 = -1 + 20*x^19 + 400*x^99
d/dx -1 + 20*x^19 + 400*x^99 = 39600*x^98 + 380*x^18
Exercise 7.36
import math
class Vec2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
other = self.convert2Vec2D(other)
return Vec2D(self.x + other.x, self.y + other.y)
def __radd__(self, other):
other = self.convert2Vec2D(other)
return self.__add__(self, other)
def __rsub__(self, other):
other = self.convert2Vec2D(other)
return other.__sub__(self)
def __sub__(self, other):
other = self.convert2Vec2D(other)
return Vec2D(self.x - other.x, self.y - other.y)
def __mul__(self, other):
other = self.convert2Vec2D(other)
return self.x * other.x + self.y * other.y
def __rmul__(self, other):
other = self.convert2Vec2D(other)
return self.__rmul__(self, other)
def __eq__(self, other):
other = self.convert2Vec2D(other)
return self.x == other.x and self.y == other.y
def __req__(self, other):
other = self.convert2Vec2D(other)
return self.__eq__(self, other)
def __str__(self):
return '(%g, %g)' % (self.x, self.y)
def __abs__(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
def __ne__(self, other):
return not self.__eq__(other) # reuse __eq__
@staticmethod
def convert2Vec2D(other):
if isinstance(other, (list, tuple)):
return Vec2D(other[0], other[1])
else:
return other
u = Vec2D(-2, 4)
v = u + (1, 1.5)
print v
w = [-3, 2] - v
print w
Console
(-1, 5.5)
(-2, -3.5)