Skip to content

Commit e425c34

Browse files
committed
Solutions
1 parent cbdcaa2 commit e425c34

29 files changed

+2001
-1
lines changed

CH12/EX12.1.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def getSide2(self):
6161
return self.side2
6262

6363
def setSide2(self, side2):
64-
self.side1 = side2
64+
self.side2 = side2
6565

6666
def getSide3(self):
6767
return self.side3

CH13/Checkpoints

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#13.1
2+
For reading: open(filename,'r')
3+
For writing: open(filename,'w')
4+
For appending: open(filename,'a')
5+
6+
#13.2
7+
The file name string must has prefix r or with double backslash:
8+
r"c:\book\test.txt"
9+
or, "c:\\book\\test.txt"
10+
11+
#13.3
12+
A runtime error will be thrown.
13+
The current file content will overwritten.
14+
15+
#13.4
16+
os.path.isfile(filename)
17+
18+
#13.5
19+
filename.read(30)
20+
21+
#13.6
22+
s = filename.read()
23+
24+
#13.7
25+
filename.readline()
26+
27+
#13.8
28+
lines = filename.readlines()
29+
30+
#13.9
31+
No, it will return ''
32+
33+
#13.10
34+
If the read function returns ''
35+
36+
#13.11
37+
filename.write(data)
38+
39+
#13.12
40+
Using repr function. Or, using notation r"string".
41+
42+
#13.13
43+
To write numeric data, write them as strings separated by spaces.
44+
To read the numeric data, read the data, split them by spaces, and evaluate numbers values
45+
46+
#13.14
47+
filenameforReading = askopenfilename()
48+
49+
#13.15
50+
filenameforWriting = asksaveasfilename()
51+
52+
#13.16
53+
infile = urllib.request.urlopen(url)
54+
55+
#13.17
56+
decode()
57+
58+
#13.18
59+
1) Will statement3 be executed? NO
60+
2) If the exception is not caught, will statement4 be executed? NO
61+
3) If the exception is caught in the except block, will statement4 be executed? YES
62+
63+
#13.19
64+
Index out of bound
65+
66+
#13.20
67+
Divided by zero!
68+
69+
#13.21
70+
Index out of bound
71+
72+
#13.22
73+
1) Will statement5 be executed if the exception is not caught? NO
74+
2) If the exception is of type Exception3, will statement4 be executed, and will
75+
statement5 be executed? YES, both will be executed
76+
77+
#13.23
78+
raise ExceptionClass()
79+
80+
#13.24
81+
1) Preventing the program from terminating abnormally.
82+
2) Informing the user that he/she may made an error.
83+
3) The essential benefit of exception handling is to separate the detection of an error (done in a called function)
84+
from the handling of an error (done in the calling method).
85+
86+
#13.25
87+
Done
88+
Nothing is wrong
89+
Finally we are here
90+
Continue
91+
92+
#13.26
93+
Index out of bound
94+
Finally we are here
95+
Continue
96+
97+
#13.27
98+
ArithmeticError class is super class of ZeroDivisionError,
99+
So ZeroDivisionError should be placed before ArithmeticError
100+
101+
#13.28
102+
You can define a custom exception class by extending BaseException or a subclass
103+
of BaseException.
104+
105+
#13.29
106+
For writing: file = open(filename, "wb")
107+
For reading: file = open(filename, "rb")
108+
109+
#13.30
110+
To write an object: pickle.dump(data, filename)
111+
To read an object: pickle.load(filename)
112+
113+
#13.31
114+
The file is closed in the finally clause after pickle.load(infile) is executed,
115+
even though the end of file is not reached.
116+
117+
#13.32
118+
Yes.
119+

CH13/EX13.1.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# 13.1 (Remove text) Write a program that removes all the occurrences of a specified
2+
# string from a text file. Your program should prompt the user to enter a filename
3+
# and a string to be removed.
4+
5+
filename = input("Enter a filename: ").strip()
6+
string = input("Enter the string to be removed: ")
7+
file = open(filename, 'r')
8+
data = ''
9+
for line in file:
10+
data += line.replace(string, '')
11+
12+
13+
# I will create a new file instead of writing on the same file for future exercises usage.
14+
resFile = open('result', 'w')
15+
resFile.write(data)
16+
resFile.close()
17+
print("Done")

CH13/EX13.10.py

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# 13.10 (The Rational class) Modify the Rational class in Listing 8.4, Rational.py, to
2+
# throw a RuntimeError exception if the denominator is 0.
3+
4+
5+
class Rational:
6+
def __init__(self, numerator=0, denominator=1):
7+
if denominator == 0:
8+
raise RuntimeError()
9+
10+
divisor = gcd(numerator, denominator)
11+
self.__numerator = (1 if denominator > 0 else -1) \
12+
* int(numerator / divisor)
13+
self.__denominator = int(abs(denominator) / divisor)
14+
15+
# Add a rational number to this rational number
16+
def __add__(self, secondRational):
17+
n = self.__numerator * secondRational[1] + \
18+
self.__denominator * secondRational[0]
19+
d = self.__denominator * secondRational[1]
20+
return Rational(n, d)
21+
22+
# Subtract a rational number from this rational number
23+
def __sub__(self, secondRational):
24+
n = self.__numerator * secondRational[1] - \
25+
self.__denominator * secondRational[0]
26+
d = self.__denominator * secondRational[1]
27+
return Rational(n, d)
28+
29+
# Multiply a rational number to this rational
30+
def __mul__(self, secondRational):
31+
n = self.__numerator * secondRational[0]
32+
d = self.__denominator * secondRational[1]
33+
return Rational(n, d)
34+
35+
# Divide a rational number by this rational number
36+
def __truediv__(self, secondRational):
37+
n = self.__numerator * secondRational[1]
38+
d = self.__denominator * secondRational[0]
39+
return Rational(n, d)
40+
41+
# Return a float for the rational number
42+
def __float__(self):
43+
return self.__numerator / self.__denominator
44+
45+
# Return an integer for the rational number
46+
47+
def __int__(self):
48+
return int(self.__float__())
49+
50+
# Return a string representation
51+
def __str__(self):
52+
if self.__denominator == 1:
53+
return str(self.__numerator)
54+
else:
55+
return str(self.__numerator) + "/" + str(self.__denominator)
56+
57+
def __lt__(self, secondRational):
58+
return self.__cmp__(secondRational) < 0
59+
60+
def __le__(self, secondRational):
61+
return self.__cmp__(secondRational) <= 0
62+
63+
def __gt__(self, secondRational):
64+
return self.__cmp__(secondRational) > 0
65+
66+
def __ge__(self, secondRational):
67+
return self.__cmp__(secondRational) >= 0
68+
69+
# Compare two numbers
70+
def __cmp__(self, secondRational):
71+
temp = self.__sub__(secondRational)
72+
if temp[0] > 0:
73+
return 1
74+
elif temp[0] < 0:
75+
return -1
76+
else:
77+
return 0
78+
79+
# Return numerator and denominator using an index operator
80+
81+
def __getitem__(self, index):
82+
if index == 0:
83+
return self.__numerator
84+
else:
85+
return self.__denominator
86+
87+
88+
def gcd(n, d):
89+
n1 = abs(n)
90+
n2 = abs(d)
91+
gcd = 1
92+
93+
k = 1
94+
while k <= n1 and k <= n2:
95+
if n1 % k == 0 and n2 % k == 0:
96+
gcd = k
97+
k += 1
98+
99+
return gcd
100+
101+
102+
def main():
103+
try:
104+
n1 = Rational(5, 10)
105+
n2 = Rational(1, 0)
106+
print(n1 + n2)
107+
except RuntimeError:
108+
print("Cannot divide by Zero!")
109+
110+
111+
main()

CH13/EX13.11.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# 13.11 (The Triangle class) Modify the Triangle class in Programming Exercise 12.1
2+
# to throw a RuntimeError exception if the three given sides cannot form a
3+
# triangle.
4+
5+
import math
6+
7+
8+
class GeometricObject:
9+
def __init__(self, color="green", filled=True):
10+
self.__color = color
11+
self.__filled = filled
12+
13+
def getColor(self):
14+
return self.__color
15+
16+
def setColor(self, color):
17+
self.__color = color
18+
19+
def isFilled(self):
20+
return self.__filled
21+
22+
def setFilled(self, filled):
23+
self.__filled = filled
24+
25+
def __str__(self):
26+
return "color: " + self.__color + \
27+
" and filled: " + str(self.__filled)
28+
29+
30+
class Triangle(GeometricObject):
31+
def __init__(self, side1=1.0, side2=1.0, side3=1.0, color="green", isFilld=True):
32+
super().__init__(color, isFilld)
33+
self.__side1 = side1
34+
self.__side2 = side2
35+
self.__side3 = side3
36+
if not self.isLegal():
37+
raise RuntimeError()
38+
39+
def isLegal(self):
40+
return self.__side1 + self.__side2 > self.__side3 and \
41+
self.__side2 + self.__side3 > self.__side1 and \
42+
self.__side1 + self.__side3 > self.__side2
43+
44+
def getSide1(self):
45+
return self.__side1
46+
47+
def setSide1(self, side1):
48+
self.__side1 = side1
49+
50+
def getSide2(self):
51+
return self.__side2
52+
53+
def setSide2(self, side2):
54+
self.__side2 = side2
55+
56+
def getSide3(self):
57+
return self.__side3
58+
59+
def setSide3(self, side3):
60+
self.__side3 = side3
61+
62+
def getArea(self):
63+
s = (self.__side1 + self.__side2 + self.__side3) / 2
64+
area = math.sqrt(s * (s - self.__side1) * (s - self.__side2) * (s - self.__side3))
65+
return area
66+
67+
def getPerimeter(self):
68+
return self.__side1 + self.__side2 + self.__side3
69+
70+
def __str__(self):
71+
return super().__str__() + " Triangle: side1 = " + str(self.__side1) + " side2 = " + \
72+
str(self.__side2) + " side3 = " + str(self.__side3)
73+
74+
75+
def main():
76+
try:
77+
s1, s2, s3 = eval(input("Enter three sides of a Triangle: "))
78+
color = input("Enter color of a triangle: ")
79+
isFilled = bool(int(input("Is the triangle filled? (1 or 0): ")))
80+
81+
trngl = Triangle(s1, s2, s3, color, isFilled)
82+
print("Triangle's area is:", trngl.getArea())
83+
print("Triangle's perimeter is:", trngl.getPerimeter())
84+
print(trngl)
85+
except RuntimeError:
86+
print("Cannot form a triangle")
87+
88+
89+
main()

0 commit comments

Comments
 (0)