0% found this document useful (0 votes)
182 views19 pages

cs1010s Final Apr20 PDF

Uploaded by

purnamakay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
182 views19 pages

cs1010s Final Apr20 PDF

Uploaded by

purnamakay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

NATIONAL UNIVERSITY OF SINGAPORE

CS1010S—Programming Methodology
2019/2020 Semester 2

Time Allowed: 1 hour

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

Question 1: Python Expressions [10 marks]


There are two parts to this problem. Answer each part independently and separately. In each
part, one or more Python expressions are entered into the interpreter (Python shell). Determine
the response printed by the interpreter for the final expression entered and write the exact
output in the answer box. If the interpreter produces an error message, or enters an infinite
loop, explain why and clearly state the responsible evaluation step.

A. 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)

[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

Question 2: COVID Sweeper [15 marks]


Background (OK to skip) COVID Sweeper is a game invented by Ng Keng Hwee which is a
blatant rip-off of Minesweeper. It basically works the same but with mines replaced by coron-
aviruses. Source: Dr. Leong
Viruses are scattered within a rectangular grid:

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))

Provide an implementation for the function adjacent_grid . [5 marks]

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

Question 3: Counting Faster [15 marks]


Like you, Ben Bitdiddle learnt about counting change in CS1010S:
def count_change(amt, denom):
if amt < 0 or len(denom) == 0:
return 0
elif amt == 0:
return 1
else:
return count_change(amt-denom[0], denom) \
+ count_change(amt, denom[1:])

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

D. Provide an implementation which uses a dictionary, for the functions create_database ,


put , get and contains to complete Ben’s code. [4 marks]

E. We now use create_memo_cc to create a new count_change function as follows:

>>> count_change = create_memo_cc()

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

Question 4: Airborne Troopers [8 marks]


Consider the following classes:
class Trooper:
def __init__(self, *equipment):
self.equipment = list(equipment)

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 ##

A. What is the output of executing the following statements:


>>> boba = JumpJet(('Rocket Launcher', 30))

>>> 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:

class JumpJetMedic(JumpJet, Medic):


pass

The following sample execution shows the behaviour of a JumpJetMedic :


>>> kix = JumpJetMedic(('Medikit', 1)) # kix is a jumpjetting medic
>>> kix.equipment # medic's equipment includes a stretcher by default
[('Stretcher', 10), ('Jetpack', 20), ('Medikit', 1)]

>>> kix.speed()
17
>>> kix.toggle_jet()
>>> kix.speed() # kix jump jets to casualty
170
>>> kix.toggle_jet()

>>> rex = Tropper()


>>> rex.weight = 70 # rex weight is 70

>>> kix.evacuate(rex) # kix now carries rex


>>> kix.load() # total load increases by rex's weight
101

>>> kix.equipment # but equipment remains unchanged


[('Stretcher', 10), ('Jetpack', 20), ('Medikit', 1)]

>>> kix.toggle_jet() # cannot fly while carrying rex


Too heavy to fly

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]

Question 5: 42 and the Meaning of Life [2 marks]


Either: (a) explain how you think some of what you have learnt in CS1010S will be helpful for
you for the rest of your life and/or studies at NUS; or (b) tell us an interesting story about your
experience with CS1010S this semester. [2 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

Time allowed: 1 hour

Instructions (please read carefully): STUDENT NUMBER

1. Write down your student number on the right and us- A


ing ink or pencil, shade the corresponding circle in the U 0 0 0 0 0 0 0 A N
A 1 1 1 1 1 1 1 B R
grid for each digit or letter. DO NOT WRITE YOUR
HT 2 2 2 2 2 2 2 E U
NAME! NT 3 3 3 3 3 3 3 H W
4 4 4 4 4 4 4 J X
2. This answer booklet comprises TEN (10) pages, in-
5 5 5 5 5 5 5 L Y
cluding this cover page. 6 6 6 6 6 6 6 M

3. All questions must be answered in the space provided; 7 7 7 7 7 7 7


8 8 8 8 8 8 8
no extra sheets will be accepted as answers. You may 9 9 9 9 9 9 9
use the extra page behind this cover page if you need
more space for your answers.
4. You must submit only the ANSWER SHEET and no For Examiner’s Use Only
other documents. The question set may be used as Question Marks
scratch paper.
Q1 / 10
5. An excerpt of the question may be provided to aid you
in answering in the correct box. It is not the exact Q2 / 15
question. You should still refer to the original question
in the question booklet. Q3 / 15

6. You are allowed to use pencils, ball-pens or fountain Q4 / 8


pens, as you like as long as it is legible (no red color,
please). Q5 / 2

7. Marks may be deducted for i) unrecognisable hand- Total / 50


writing, and/or ii) excessively long code. A general
guide would be not more than twice the length of our
model answers.
Answer Sheet CS1010S Final Assessment

This page is intentionally left blank.


Use it ONLY if you need extra space for your answers, and indicate the question number
clearly as well as in the original answer box. Do NOT use it for your rough work.

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]

def adjacent_mines(cases, i, j):

Question 2B [5 marks]

def adjacent_grid(cases, row, col):

4
Answer Sheet CS1010S Final Assessment

Question 2C [5 marks]

def safe_paths(grid):

Question 3A [2 marks]

count_change(100, (50, 25, 10, 5))

Question 3B [2 marks]

Time:

Space:

5
Answer Sheet CS1010S Final Assessment

Question 3C [3 marks]

Question 3D [4 marks]

def create_database():

def put(db, ans, *n):

def get(db, *n):

def contains(ab, *n):

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

Question 5 42 and the Meaning of Life [2 marks]

9
Answer Sheet CS1010S Final Assessment

This page is intentionally left blank.


Use it ONLY if you need extra space for your answers, and indicate the question number
clearly as well as in the original answer box. Do NOT use it for your rough work.

— END OF ANSWER SHEET —

10

You might also like