Date: January 14th, 2014
Time: 14:10-16:00
Open book; turn off computer & mobile phone
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
# Defining how to print out an object
class Rational:
def __init__(self, n, d):
self.numerator = n
self.denominator = d
def __str__(self):
return str(n) + '/' + str(d)
def main():
a = Rational(14, 8)
print(a)
main()
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
# Reduce a rational number automatically before it is printed out
def gcd(a, b): # Greatest Common Divisor
if b == 0:
return a
else:
return gcd(b, a % b)
class Rational:
def __init__(self, n, d):
self.numerator = n
self.denominator = d
def reduce(self):
g = gcd(self.numerator, self.denominator)
self.numerator = self.numerator // g
self.denominator = self.denominator // g
def __str__(self):
return str(self.numerator) + '/' + str(self.denominator)
def main():
a = Rational(14, 8)
print(a)
main()
# ASCII code (P.132)
msg = "DRO ZYBD XEWLOB SC DGOXDI DRYECKXN YXO REXNBON KXN PYBDI YXO"
key = 16
plaintext = ""
for ch in msg:
if ch.isalpha():
plaintext = plaintext + chr( (ord(ch) - 65 + key) % 26 + 65 )
else:
plaintext = plaintext + ch
print(plaintext)