Question 1

advertisement
Written exam example - FP, 2015
Analyze the code of questions 1-6 and (a) show the result of executing that code. Explain
your answer briefly (b) by indicating the memory representation when the program stops
and (c) by indicating why the program crashes (if applicable).
Q1.
1 a=1
5
print (id(a) == id(b))
Types
2 b=a+1
6
print (id(a) == id(c))
3 c=a
7
print (id(b) == id(d))
4 d=2
Q2.
Types
1
2
3
4
a = [0]
b=a
a = a + [1]
b.append(2)
5
6
7
8
9
print (a)
print (id(a) == id(b))
b.append(a)
print(b)
print (b[0][2])
Q3.
Functions
1
2
3
4
5
6
a=1
def f(a):
a=2
def g(a):
a[0] = 2
x=3
7
8
9
10
11
12
f(x)
print (a)
print (x)
x = [3, 3]
g(x)
print (x)
Q4.
Modules
1 #module1.py
2 a=1
3 def f():
4
return a + 1
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
#module2.py
import module1
a = module1.a
def f():
global a
a=2
return a + 1
print(f())
print(module1.f())
print (a)
Q5.
Custom types
1 class A:
2
def f(self): print ("f")
3 class B(A):
4
def __init__(self):
5
self.la = []
6
def add(self, a):
7
self.la.append(a)
8
return self
9
def f(self):
10
for a in self.la: a.f()
11
12
13
14
15
a = A()
b = B().add(a).add(A())
b.add(B().add(A()).add(B().add(a)))
a.f()
b.f()
Q6.
Custom types
1 class Rational:
def __init__(self, m=0, n=1):
2
if n == 0:
3
raise ValueError()
4
self.m = m
5
self.n = n
6
def __eq__(self, o):
7
return self.m == o.m and self.n == o.n
8
9
10
11
12
13
14
15
16
17
18
def test1():
a = Rational(2, 4)
assert a.m == 2
b = Rational(2, 4)
assert id(a) != id(b)
assert a == b
try:
Rational(1, 0)
assert False
except ValueError:
pass
test1()
Write the documentation of a function which inserts a number into an ordered
list of numbers.
Write test cases for that function based on its specification.
Write the body of the function defined at P7.
P8. Body
P9. Divide et Write an iterative function which computes the power x^n, where x is a real
number and n natural number. Apply a divide et impera strategy in order to
impera,
reduce the number of multiplications – e.g. you can proceed as the following
iterative
example shows 2^9 = 2*2^8 = 2*4^4 = 2*16^2 = 2*256 = 512.
Determine the best case and worst case complexity for the function defined at
P10.
P10.
Complexity
Write a recursive function which computes the gcd of two natural numbers.
Apply a divide et impera strategy as suggested by the following examples
P11.
Recursivity gcd(8, 6) = 2 * gcd (8/2, 6/2), and gcd (8, 9) = gcd(8/2, 9).
P7. Doc and
test
P12.
Write a class MyTodos which represents a list of strings (“todos”) such
Custom type that the following code works as specified by the comments.
todos = MyTodos()
todos.add(“prepare fp”).add(“learn python”).add(“learn JS”)
# todos contains three items
for todo in todos.filter(“learn”): # filter and print the todos containing “learn”
print (todo) # only “learn python” and “learn js” will be printed
Download