(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).
# Define a Class
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
class Rational:
def __init__(self, n=0, d=1):
self.numerator = n
self.denominator = d
def reduce(self):
d = gcd(self.numerator, self.denominator)
self.numerator = self.numerator // d
self.denominator = self.denominator // d
def __str__(self):
self.reduce()
if self.denominator == 1:
result = str(self.numerator)
else:
result = str(self.numerator)+'/'+str(self.denominator)
return result
def main():
a = Rational(36)
b = Rational(24, 1)
c = Rational(36, 24)
qList = [a, b, c]
for q in qList:
print(q)
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).
# Method of an Object
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
class Rational:
def __init__(self, n=0, d=1):
self.numerator = n
self.denominator = d
def reduce(self):
d = gcd(self.numerator, self.denominator)
self.numerator = self.numerator // d
self.denominator = self.denominator // d
def __str__(self):
self.reduce()
if self.denominator == 1:
result = str(self.numerator)
else:
result = str(self.numerator)+'/'+str(self.denominator)
return result
def add(self, q):
n = self.numerator * q.denominator + self.denominator * q.numerator
d = self.denominator * q.denominator
return Rational(n, d)
def main():
c = Rational(36, 24)
d = Rational(24, 36)
e = c.add(d)
qList = [c, d, e]
for q in qList:
print(q)
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).
# Sorting a List of Objects
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
class Rational:
def __init__(self, n=0, d=1):
self.numerator = n
self.denominator = d
def reduce(self):
d = gcd(self.numerator, self.denominator)
self.numerator = self.numerator // d
self.denominator = self.denominator // d
def __str__(self):
self.reduce()
if self.denominator == 1:
result = str(self.numerator)
else:
result = str(self.numerator)+'/'+str(self.denominator)
return result
def add(self, q):
n = self.numerator * q.denominator + self.denominator * q.numerator
d = self.denominator * q.denominator
return Rational(n, d)
def reciprocal(q):
return q.denominator / q.numerator
def main():
c = Rational(36, 24)
d = Rational(24, 36)
e = c.add(d)
qList = [c, d, e]
qList.sort(key=reciprocal)
for q in qList:
print(q)
main()