Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Part 1: Algorithmic Thinking

[4 marks]
Question 1
What is the output of the following code:
def fun(string):
counter = 0
for ch in string.lower():
if ch in "aeiuo":
counter += 1
return counter

print fun("Albatross")
A: 3

[5 marks]
Question 2
What is the output of the following code:
wlist = [5,10,4,2]
daily_limit = 3
transactions = 0
balance = 12
while balance and transactions < daily_limit:
balance -= wlist.pop()
transactions += 1
print transactions,balance,wlist
A: 1 10 [5, 10, 4]
2 6 [5, 10]
3 -4 [5]

1
[8 marks]
Question 3
The following program is intended to calculate the sum of an arbitrarily-nested list of integers, but
the lines are out of order and all indentation has been lost. Put the line numbers in the correct order
and introduce appropriate indentation (indent the line numbers to show how the corresponding
lines would be indented in your code).
1 return sum
2 sum = sum + element
3 else:
4 if type(element) == list:
5 sum = sum + rec_sum(element)
6 def rec_sum(num_list):
7 for element in num_list:
8 print rec_sum([1,[3,5],9,[-1,[4]]])
9 sum = 0
A: 6
9
7
4
5
3
2
1
8

2
[10 marks]
Question 4
Answer the following questions based on the following code, and the indicated line numbers:
1 tups = [("luke","cake"),("marco","changing"),("qc","crows"),\
2 ("marco","dijkstra"),("tim","totoro")]
3
4 def fun(tup_lst):
5 d = {}
6 for i,j in tup_lst:
7 try:
8 d[i].append(j)
9 except KeyError:
10 d[i] = [j]
11 return d
12
13 faves = fun(tups)

(a) What does line 6 do?


A: it iterates over each tuple in the list tup_lst assigning i,j to the respective elements of the tuple

(b) What is the purpose of line 10, and what other line(s) potentially cause it to be executed?
A: it initialises the list of values associated with key i to the single value j; an exception at line 8 causes it to be executed

(c) After executing the code, what is the value of faves?


A: {’luke’: [’cake’], ’qc’: [’crows’], ’marco’: [’changing’, ’dijkstra’], ’tim’: [’totoro’]}

3
[12 marks]
Question 5
The following is an implementation of the function valid_ip that takes a single string argument
ip, and is intended to return True if and only if ip is a valid IPv4 address, and False other-
wise. Recall that a valid IPv4 address is made up of four integers in the range 0 to 255, inclusive,
separated by full stops (.).
def valid_ip(ip):
vals = 0
for val in ip.split("."):
correct = False
for i in range(255):
if val == str(i):
correct = True
break
if not correct:
return False
return True

(a) Provide an example of a valid IP for which valid_ip() would return True (i.e. the function
would perform correctly).
A: Any valid IP not including the value 255

(b) Provide an example of a valid IP for which valid_ip() would return False, despite it being
valid.
A: Any valid IP including the value 255

(c) Provide an example of an invalid IP for which valid_ip() would return True, despite it being
invalid.
A: Any sequence of 0–3 or 5+ numbers in the range [0, 254]

(d) Provide an example of an invalid IP for which valid_ip() would return False (i.e. the func-
tion would perform correctly).
A: Anything else (e.g. number too high, or negative, or float, or contains letter ...)

4
Part 2: Constructing Programs
[12 marks]
Question 6
The following function infreq_words() is intended to return a list of str identifying the top-
num most infrequent words in doc (the URL of a file, in the form of a str), where num stipulates
the number of results to return as an int (with default value 10). The results should be sorted
in ascending order of frequency, and if there are multiple words with the same frequency, they
should be sub-sorted alphabetically.
1 from collections import defaultdict
2 from urllib import urlopen
3
4 def infreq_words(doc,num=10):
5 words = defaultdict(int)
6 for word in urlopen(doc).readlines().split()
7 word = word.lower().rstrip(",.:;!?-'"")
8 if word:
9 words[word] = 1
10 return sorted([(freq,word) for word,freq in words.items()])[:n]
The code contains several errors. Identify exactly three (3) errors and specify: (a) the line number
where the error occurs; (b) the type of error, as syntax, logic or runtime; and (c) how you would fix
each error, in the form of corrected code.
A: Three out of:

1. missing colon at end of line 6 (syntax)

2. readlines() should be read() on line 6 (runtime)


3. n should be num on line 10 (runtime)
4. = should be += on line 9 (logic)
5. " should be escaped line 7 (syntax)
6. line 10 should return just each word not freq,word tuples (logic)

5
[10 marks]
Question 7
In this question, you are asked to generate an HTML document containing a ranked scoreboard
of all players in scores in the form of a table such as the following:

Complete the code below to generate the required HTML document, populating the table relative
to the contents of scores. For each of the numbered boxes (the size of which isn’t necessarily rep-
resentative of the length of the replacement code snippet), provide a snippet of code to complete
the program, based on the above description of what output it should generate.
scores = [(10,'somecallme'),(15,'mightymarco'),\
(12,'quincy_ngones'),(13,'iamyourfather')]
print """Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
<title>Scoreboard</title>
</head>
<body>
< 1 >
<tr><th>Rank 2 """
3
for (points,player) in sorted(scores,reverse=True):
4
rank += 1
print """</table>
5
</html>
"""
A:
1 table border="1"
2 </th><th>Player</th><th>Score</th></tr>
3 rank = 1
4 print ’<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>’.format(rank,player,points)
5 </body>

6
[20 marks]
Question 8
“Tic-tac-toe” (also known as “noughts and crosses”) is a two-player game where players take it
in turns to place crosses (“X”) and noughts (“O”), respectively, on a 3×3 grid, until either: (1) one
player has connected three marks of the same type (either a nought or a cross) along a row, column
or diagonal of the grid, in which case that player wins the game; or (2) no three marks of the same
type are connected and all cells in the grid are filled, in which case the game is drawn.
For example, the example to the left below is an instance of a winning game for the “crosses”
player (based on three crosses being connected across the diagonal, as indicated), and the example
to the right below is an instance of a drawn game:

(a) Complete the code below to implement Python function init_board(), which returns a dic-
tionary containing one element per grid cell, where each dictionary key is a tuple of two integers
representing the (x,y) coordinates of the cell (e.g. (0,0) or (2,1)), and each value is None.
[5 marks]

def init_board():
board = {}
# your code goes after this
A:
for i in range(3):
for j in range(3):
board[(i,j)] = None
return board

7
(b) Write a function place_mark, which takes the current board board (as specified in part (a)), a
2-tuple position pos and a marker mark (with value "X" or "O"), and returns the updated board
after mark has been placed at position pos. You may assume that board, pos and mark are valid
inputs in your code.
[5 marks]
A:
def place_mark(board,pos,mark):
board[pos] = mark
return board

8
(c) Complete the following code to implement function find_winner, which takes the current
board board (as specified in (a)) as input and determines whether: (a) one of the two players has
won the game, in which case it returns their “marker” (i.e. the string value associated with their
plays in board); (b) whether the game is drawn, in which case it returns the string "draw"; or (c)
whether the game is still undecided, in which case it returns None.
[10 marks]

def find_winner(board):
if board[0,0] == board[1,1] == board[2,2]:
return board[1,1]
# your code goes after this
A:
if board[0,2] == board[1,1] == board[2,0]:
return board[1,1]
for i in range(3):
if board[i,0] == board[i,1] == board[i,2]:
return board[i,0]
if board[0,i] == board[1,i] == board[2,i]:
return board[0,i]
for i in range(3):
for j in range(3):
if not board[i,j]:
return None
return "draw"

9
[16 marks]
Question 9
Write a function repeat_word that takes a single string argument word, and returns True if word
is made up of two or more repeats of a sub-string, and False otherwise. For example, booboo
contains the sub-string boo repeated twice. The following are example outputs of the function:
>>> repeat_word("booboo")
True
>>> repeat_word("hahaha")
True
>>> repeat_word("banana")
False
>>> repeat_word("a")
False
You may assume that word is a non-empty string in your solution.
A:
def repeat_word(word):
word_len = len(word)
for substr_len in range(1,word_len/2+1):
if word == word[:substr_len]*(word_len/substr_len):
return True
return False

10
Part 3: Conceptual Questions
[13 marks]
Question 10: Applied Questions
(a) Explain the role of the “public key” and “private key” in “public key encryption”, when se-
curely transferring a file. For each of the “sender” and “receiver” of the file, state which keys they
have access to.
[5 marks]
A: • public key = used to encrypt message

• private key = used to decrypt message

• public key = accessible to both sender and receiver

• private key = accessible to receiver and not sender


(b) A “genome” can be represented as a sequence of “bases”, each of which can be encoded as a
two-bit value. Assuming that a megabit is 1,000,000 bits, how many megabytes are required to
encode a 16 million base genome?
[4 marks]
A: 4MB
(c) What are the two primary approaches to “software testing”? Briefly illustrate each with an
example.
[4 marks]
A: • execution-based validation (e.g. unit testing)

• non-execution-based validation (e.g. pair programming)

[10 marks]
Question 11: Theoretical Questions
(a) What are the two (2) principal computational desiderata for algorithms?
[4 marks]
A: • correctness

• efficiency
(b) Explain the processes of “sampling” and “quantisation” in the context of “scanning” a physical
image to generate a digital representation. You may optionally use a diagram in your answer.
[6 marks]
A: • sampling = partitioning of image into regular-sized segments (pixels)

• quantisation = conversion of each pixel into a digital value

11

You might also like