cs1010s Final Apr20 PDF
cs1010s Final Apr20 PDF
CS1010S—Programming Methodology
2019/2020 Semester 2
INSTRUCTIONS TO STUDENTS
1. The assessment paper contains FIVE (5) questions and comprises NINE (9) pages in-
cluding this cover page.
2. Weightage of each question is given in square brackets. The maximum attainable score
is 50.
3. This is a CLOSED book assessment, but you are allowed to bring ONE double-sided
A4 sheet of notes for this assessment.
4. Enter all your answers in the correct space provided on Examplify.
5. Marks may be deducted for excessively long code. A general guide would be not more
than twice the length of our model answers.
6. Common List and Dictionary methods are listed in the Appendix for your reference.
CS1010S Final Assessment
def f(lst):
for i in lst.copy():
if len(i) < 2:
i.append(1)
if sum(i) < 5:
i.pop()
else:
lst.extend(i)
print(lst)
return lst
print(lst is f(lst))
print(lst)
[5 marks]
B. s = 'mississipi'
d = {}
while s:
if s[0] not in d:
d[s[0]] = s[1]
else:
d.pop(s[0])
s = s[1:]
print(d)
[5 marks]
2
CS1010S Final Assessment
The shaded red cells show the infectious zones for each virus, which are the 8 adjacent cells
of a virus, as well as the middle cell containing the virus itself. Darker reds shows overlapping
infectious zones from two or more viruses around that cell.
A. Suppose the position of each virus in the grid is given as a sequence of (row, col) pairs.
For example, for the grid shown above, the sequence will be:
seq = ((0, 2), (1, 5), (2, 4), (3, 6), (4, 0))
The function adjacent_viruses(seq, row, col) takes as input the positions of the viruses,
a row and column number. It returns the number of viruses surrounding and within the cell in
the given row and column. For example:
>>> adjacent_viruses(seq, 2, 5)
3
>>> adjacent_viruses(seq, 1, 5)
2
>>> adjacent_viruses(seq, 4, 4)
0
Provide an implementation for the function adjacent_viruses . You may assume that the
inputs are always valid and will not exceed the bounds of the grid. [5 marks]
3
CS1010S Final Assessment
B. Knowing the position of each virus is good, but having a map of the infectious zone is
better.
The function adjacent_grid(seq, height, width) that takes as inputs the sequence of
viruses’ position of the viruses, and the height and width of the grid. It returns a 2D grid,
represented as a tuple of rows, where each row is a tuple of integers indicating number of
adjacent viruses for each respective cell. For example:
>>> adjacent_grid(seq, 6, 7)
((0, 1, 1, 1, 1, 1, 1),
(0, 1, 1, 2, 2, 2, 1),
(0, 0, 0, 1, 2, 3, 2),
(1, 1, 0, 1, 1, 2, 1),
(1, 1, 0, 0, 0, 1, 1),
(1, 1, 0, 0, 0, 0, 0))
C. Suppose we want to walk starting from the (0, 0) corner of the grid to the opposite corner,
taking care to avoid the infectious zone of each virus. We are only allowed to walk along
non-decreasing row and column numbers, i.e. only down or right as viewed in the illustration.
For the given sequence of viruses, there are three possible paths as shown above.
Implement the function safe_paths(grid) , which takes as input the grid representation cre-
ated in Part B. The function returns the number of paths where we can safely get from the (0,
0) corner to the opposing corner. For example:
>>> safe_paths(adjacent_grid(seq, 6, 7))
3
[5 marks]
4
CS1010S Final Assessment
A. Ben’s code looks a little different from what we used in class. State the function call
with the appropriate inputs to obtain the number of ways to change 1 dollar (100 cents) using
50-cent, 25-cent, 10-cent and 5-cent coin denominations. [2 marks]
B. What is the order of growth in terms of time and space for count_change . [2 marks]
C. count_change runs too slowly for Ben. He notices that it does a lot of repeated operations.
“If only I have some way to remember and reuse past computations,” Ben thinks. Then he
remembered you have given him some database ADT in the past, and wrote the following
code:
def create_memo_cc():
db = create_database()
def memo_cc(amt, denom):
if amt < 0 or len(denom) == 0:
return 0
elif amt == 0:
return 1
elif contains(db, amt, denom) :
return get(db, amt, denom)
else:
ans = count_change(amt-denom[0], denom) \
+ count_change(amt, denom[1:])
put(db, ans, amt, denom)
return ans
return memo_cc
Assume the functions provided (highlighted above) works correctly. Unfortunately, the code
still runs slowly like before. Describe the problem with Ben’s code and how it can be fixed.
[3 marks]
5
CS1010S Final Assessment
What is the order of growth in terms of time and space for this new version of count_change
in the long term, i.e. after we run count_change for m times, where m is a very large number
and for very large values of amt while keeping the same coin denominations? [2 marks]
F. Ben realizes that he does not have an infinite number of coins. So he decided to tweak his
code to take in a dictionary of available coins. For example, {50: 2, 25: 2, 10: 2, 5: 2}
means he has two coins of each denomination.
Somehow, he is not able to speed up his new function with the same technique. Suggest a
reason why this is so. [2 marks]
6
CS1010S Final Assessment
def load(self):
return sum(map(lambda eq: eq[1], self.equipment))
def speed(self):
return 20 - (self.load() // 10)
class JumpJet(Trooper):
def __init__(self, *equipment):
super().__init__(('Jetpack', 20), *equipment)
self.flying = False
def toggle_jet(self):
if not self.flying and self.load() > 100:
print('Too heavy to fly')
else:
self.flying = not self.flying
def speed(self):
return super().speed() * (10 if self.flying else 1)
class Medic(Trooper):
## Incomplete. To be answered in Part B ##
>>> print(boba.speed())
>>> boba.toggle_jet()
>>> print(boba.speed())
[3 marks]
7
CS1010S Final Assessment
B. Your friend Jango wishes to create a JumpJetMedic which is both a JumpJet and a
Medic and writes the following code:
>>> kix.speed()
17
>>> kix.toggle_jet()
>>> kix.speed() # kix jump jets to casualty
170
>>> kix.toggle_jet()
Being the lazy guy Jango is, he has left you to implement the class Medic . Using OOP prin-
ciples, provide a minimal implementation of Medic , which is a subclass of Trooper , that
satisfies the above sample execution. Redundant code or methods will be penalised.
[5 marks]
— END OF PAPER —
8
CS1010S Final Assessment
Appendix
Parts of the Python documentation is given here for your reference.
List Methods
• list.append(x) Add an item to the end of the list.
• list.extend(iterable) Extend the list by appending all the items from the iterable.
• list.insert(i, x) Insert an item at a given position.
• list.remove(x) Remove the first item from the list whose value is x. It is an error if
there is no such item.
• list.pop([i]) Remove the item at the given position in the list, and return it. If no
index is specified, removes and returns the last item in the list.
• list.clear() Remove all items from the list
• list.index(x) Return zero-based index in the list of the first item whose value is x.
Raises a ValueError if there is no such item.
• list.count(x) Return the number of times x appears in the list.
• list.sort(key=None, reverse=False) Sort the items of the list in place.
• list.reverse() Reverse the elements of the list in place.
• list.copy() Return a shallow copy of the list.
Dictionary Methods
• dict.clear() Remove all items from the dictionary.
• dict.copy() Return a shallow copy of the dictionary.
• dict.items() Return a new view of the dictionary’s items ( (key, value) pairs).
• dict.keys() Return a new view of the dictionary’s keys.
• dict.pop(key[, default]) If key is in the dictionary, remove it and return its value,
else return de f ault. If de f ault is not given and key is not in the dictionary, a KeyError
is raised.
• dict.update([other]) Update the dictionary with the key/value pairs from other,
overwriting existing keys. Return None .
• dict.values() Return a new view of the dictionary’s values.
— H A P P Y H O L I D A Y S ! —
9
CS1010S — Programming Methodology
School of Computing
National University of Singapore
Final Assessment
Answer Sheet
2019/2020 Semester 2
2
Answer Sheet CS1010S Final Assessment
Question 1A [5 marks]
lst = [[1], [2, 2], [3, 3, 3]]
def f(lst):
for i in lst.copy():
if len(i) < 2:
i.append(1)
if sum(i) < 5:
i.pop()
else:
lst.extend(i)
print(lst)
return lst
print(lst is f(lst))
print(lst)
Question 1B [5 marks]
s = 'mississipi'
d = {}
while s:
if s[0] not in d:
d[s[0]] = s[1]
else:
d.pop(s[0])
s = s[1:]
print(d)
3
Answer Sheet CS1010S Final Assessment
Question 2A [5 marks]
Question 2B [5 marks]
4
Answer Sheet CS1010S Final Assessment
Question 2C [5 marks]
def safe_paths(grid):
Question 3A [2 marks]
Question 3B [2 marks]
Time:
Space:
5
Answer Sheet CS1010S Final Assessment
Question 3C [3 marks]
Question 3D [4 marks]
def create_database():
Question 3E [2 marks]
Time:
Space:
6
Answer Sheet CS1010S Final Assessment
Question 3F [2 marks]
Question 4A [3 marks]
7
Answer Sheet CS1010S Final Assessment
Question 4B [5 marks]
8
Answer Sheet CS1010S Final Assessment
9
Answer Sheet CS1010S Final Assessment
10