Exercises for Lesson 21
Exercise 0: List methods, revisited
Let us take another look at the list methods we talked about last week. Recall that most of these modify the list, and most of them return None
.
Part a: remove
and sort
What is printed by the following code snippet?
s1 = [2,1,4,3]
s2 = ['c', 'a', 'b']
r1 = s2.remove('a')
r2 = s1.sort()
print(r1, r2)
print(s1)
print(s2)
Part b: append
, index
, pop
, and insert
What is printed by the following code snippet?
s1 = [2,1,4,3]
s2 = ['c', 'a', 'b']
r1 = s1.append([s2.index('b')])
r2 = s2.pop(s1.pop(0))
r3 = s2.insert(s1[0], 'd')
print(r1, r2, r3)
print(s1)
print(s2)
Exercise 1: Inheritance and method calls
The following program defines four classes. Given the constructor used for each object, what is printed?
class A:
def __init__(self, val):
self.value = val # not a bug -- these don't have to match!
def doTheThing(self):
print("Called from A:", self.value)
class B(A):
def __init__(self, value):
A.__init__(self, value) # call the parent constructor to set self.value
class C(B):
def __init__(self, v, otherVal):
B.__init__(self, v) # call the parent, which eventually sets self.value
self.otherVal = otherVal
def doTheThing(self):
print("Called from C:", self.otherVal * self.value)
class D(B):
def __init__(self, value):
self.value = value * 2 # just set self.value ourselves
def main():
a = A(4)
b = B(22)
c = C(10, 7)
d = D(55.515)
for obj in [a,b,c,d]:
obj.doTheThing()
if __name__ == "__main__":
main()