(10%) Determine whether the following code has syntax errors or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
# Define a class for Polynomial (P.305)
class Polynomial:
def __init__(self, aList):
self.coefficients = aList
def __str__(self):
def needPlus(coefficient, order):
if order == 0:
necessity = False
else:
if coefficient > 0:
necessity = True
else:
necessity = False
return necessity
result = ""
cList = self.coefficients
for i in range( len(cList) ):
a = cList[i] # coefficient
if i == 0:
expo = ''
elif i == 1:
expo = 'x'
else:
expo = "x**" + str(i)
if a != 0:
if needPlus(a, i):
if a == 1: # i must be gt 0, because needPlus
result = result + "+" + expo
else:
result = result + "+" + str( a ) + expo
else:
if a == -1 and i > 0:
result = result + '-' + expo
else:
result = result + str(a) + expo
return result
p1 = Polynomial([-1, -1, 3])
p2 = Polynomial([1, -3, 0, -1])
print(p1)
print(p2)
(10%) Determine whether the following code has syntax errors or
not. If it is correct, predict its output. If it is
incorrect, point out the mistake(s).
# Sorting a List (P.354)
class Student:
def __init__(self, i, n, s):
self.id, self.name, self.score = i, n, s
def __str__(self):
return str(self.id) + ' ' + self.name + ' ' + str(self.score)
def getScore(self):
return self.id
def getScore(self):
return self.score
students = [Student(580, "Alice", 35),
Student(191, "Bob", 75),
Student(641, "Charlie", 76),
Student(813, "Dennis", 27),
Student(809, "Emily", 79),
Student(568, "Fiona", 65) ]
students.sort(key=Student.getScore)
print( students[2] )