Exam 2019s1 Solution
Exam 2019s1 Solution
[10 marks]
Question 1
Evaluate the following expressions, and provide the output in each case.
A: 'yarra trams'
(b) 7 / 2 * 2
A: 7.0
A: True
A: 'thorin'
1
[9 marks]
Question 2
What are the final values of each of the variables indicated below, on completion of execution of
the following code:
VALUES = '2A'
SUITS = 'SHDC'
PLAYERS = 2
ROUNDS = 4
deck = []
for value in VALUES:
for suit in SUITS:
deck.append(value + suit)
hands = []
for i in range(PLAYERS):
hands.append([])
for i in range(ROUNDS):
for player in range(PLAYERS):
hands[player].append(deck.pop())
(a) i
A: 3
(b) deck
A: []
(c) hands
A: [['AC', 'AH', '2C', '2H'], ['AD', 'AS', '2D', '2S']]
2
[10 marks]
Question 3
The following code is intended to calculate a list of valid “old school” vs. “new school” superhero
running races. The rules are:
1. “old school” characters are defined as those who were created prior to a given year, and
“new school” characters are those created in the given year or later
2. each old school superhero races against each new school superhero whose costume is a dif-
ferent colour to their own
3. superheroes with the same colour costumes don’t race against one another—that would just
be confusing! Such pairings are deemed invalid
The code takes the form of the definition of a function called race_list, which takes two argu-
ments:
• afile: a CSV file containing superhero data, including their name, the year they were cre-
ated and their costume colour
• year: the year used to distinguish “old school” from “new school” superheroes
and returns a 2-tuple containing: (1) a sorted list of valid races (as strings); and (2) a count of
invalid pairings of superheroes (on the basis of their costumes being the same colour).
An example input for afile is the file superheroes.csv:
name,year,colour
Hedgehog Man,1965,brown
Captain Penguin,1962,purple
The Mystifier,1973,purple
Telephone Girl,1978,green
Little Llama,1991,beige
3
As presented, the lines of the function are out of order. 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), by placing line numbers in the table below the code (one
line number per row in the table). Note that the provided code makes use of a semi-colon (“;”)
at two different locations, to combine two statements (to initialise variables) into a single line of
code.
1 if old[pair[0]] != new[pair[1]]:
2 old = {}; new = {}
3 with open(afile) as f:
4 new[row['name']] = row['colour']
5 else:
6 old[row['name']] = row['colour']
7 for pair in itertools.product(old, new):
8 invalid += 1
9 if int(row['year']) < year:
10 races.append(f'{pair[0]} vs. {pair[1]}')
11 for row in csv.DictReader(f):
12 else:
13 return (sorted(races), invalid)
14 def race_list(afile, year):
15 races = []; invalid = 0
Answer:
14
2
3
11
9
6
5 OR 12
4
15
7
1
10
12 OR 5
8
13
4
14
2
3
11
9
6
5 OR 12
4
15
7
1
10
12 OR 5
8
13
5
[9 marks]
Question 4
The following function is intended to work out the value of the optimal combination of items to
place in a bag in terms of maximising the value of the items, subject to a weight limit on the bag.
It takes two arguments:
• capacity: the total weight that can be held by the bag
• items: a list of items, each of which is represented as a dictionary storing the weight and
value of that item
and returns the maximum value of combined items that can be achieved subject to the weight
constraint.
5 cur_item = items(0)
6
7 if cur_item['weight'] >= capacity
8 return rec_knapsack(capacity, items)
9
10 take_value = (cur_item['value']
11 + rec_knapsack(capacity - cur_item['value'], items[1:]))
12 leave_value = rec_knapsack(capacity, items[1:])
13 return max(take_value, leave_value)
A: Three out of:
6
[16 marks]
Question 5
The code on the next page is intended to validate a CSV row as containing the following four
fields:
3. a last name, in the form of an ASCII string, noting that the field may be blank (i.e. an empty
string) if the individual does not have a last name
4. a plain text password, in the form of an ASCII string between 8 and 12 characters in length
(inclusive), including at least one lower-case letter, one upper-case letter, and one punctua-
tion mark from: (a) a comma (“,”), (b) a full stop (“.”), (c) an exclamation mark (“!”), and
(d) a question mark (“?”).
If a valid CSV row is provided to the code (as a string input), the output of the code should be a
4-element list of the four values, each as a string; if an invalid CSV is provided to the code, the
output should be None.
7
def valid_name(name):
try:
assert name.isalpha()
name.encode('utf-8').decode('ascii')
except AssertionError:
return False
return True
def validate_row(row):
ROW_LENGTH = 4
STAFFID_DIGITS = 5
MIN_PASSWORD_LEN = 8
MAX_PASSWORD_LEN = 12
PUNCT = ',.!? '
fields = row.split(",")
try:
assert len(fields) == ROW_LENGTH
staffid = fields.pop(0)
assert 10**(STAFFID_DIGITS-1) <= int(staffid) < 10**STAFFID_DIGITS
given_name = fields.pop(0)
assert given_name and valid_name(given_name)
last_name = fields.pop(0)
assert valid_name(last_name)
password = fields.pop(0)
assert MIN_PASSWORD_LEN <= len(password) <= MAX_PASSWORD_LEN
contains_lower = contains_upper = contains_punct = False
for letter in password:
if letter.islower():
contains_lower = True
elif letter.isupper():
contains_upper = True
elif not letter.strip(PUNCT):
contains_punct = True
assert contains_lower and contains_upper and contains_punct
except (AssertionError, ValueError):
return None
return row.split(",")
8
The provided code is imperfect, in that it sometimes correctly detects valid and invalid rows,
but equally, sometimes misclassifies a valid row as being invalid, and sometimes misclassifies an
invalid row as being valid.
(a) Provide an example of a valid row that is correctly classified as such by the provided code (i.e.
a valid row input where the return value is the row broken down into a list of valid fields):
A: staff ID with 5 digits and no leading 0; non-empty first name; non-empty last name; valid password 8–12 characters, with 1+
lower-case letter, 1+ upper-case letter, and 1+ punctuation mark (not a comma)
(b) Provide an example of an invalid row that is correctly classified as such by the provided code
(i.e. an invalid row input where the return value is None):
A: staff ID wrong number of digits (or not all numbers); empty first name; password wrong number of characters or missing
category of letter or non-ASCII character; wrong number of fields
(c) Provide an example of an invalid row that is incorrectly classified as a valid row by the pro-
vided code (i.e. an invalid row input where the return value is an erroneous list of valid fields):
(d) Provide an example of a valid row that is incorrectly classified as an invalid row by the pro-
vided code (i.e. a valid row input where the return value is None):
A: staff ID starts with 0 OR comma in password OR empty last name OR numbers in names OR > digit IDs with leading zeroes
9
Part 2: Generating Code
[8 marks]
Question 6
Rewrite the following function, replacing the while loop with a for loop, but preserving the re-
mainder of the original code structure:
def n_green_bottles(n):
while n > 0:
b_word = 'bottles'
if n == 1:
b_word = b_word[:-1]
print(f'{n} green {b_word}, sitting on the wall!')
n -= 1
A:
def n_green_bottles(n):
for n in range(n, 0, -1):
b_word = 'bottles'
if n == 1:
b_word = b_word[:-1]
print(f'{n} green {b_word}, sitting on the wall!')
10
[10 marks]
Question 7
Write a single Python statement that generates each of the following exceptions + error messages,
assuming that it is executed in isolation of any other code.
11
[20 marks]
Question 8
“Homophily” is a sociological theory that people are more likely to be friends with those who
are similar to themselves. We can quantify how homophilous a social network is by measuring
the proportion of each person’s friends who share some characteristics (or “belong to the same
group”) as them. Network homophily is then defined as the average of these proportions over all
people in the network.
The code provided below calculates the network homophily of a network net with respect to
groups. A network is specified as a dictionary of sets of friends of each person. Groups are speci-
fied as a list of sets of people belonging to the same group. The function returns the proportion of
a person’s friends who belong to the same group as them, averaged over all people in the network.
You can assume that net contains at least two people, that each person has at least one friend,
that all people contained in groups are found in net, and that each person belongs to exactly one
group.
12
def network_homophily(net, groups):
1
group_id = 0
while group_id < len(groups):
2
membership[member] = group_id
group_id += 1
proportions = []
for person in net:
same_count = 0
3
for neighbour in neighbours:
4
same_count += 1
proportions.append(same_count / len(neighbours))
5
return average_proportion
13
Part 3: Conceptual Questions and Applications of Computing
Question 9: Computing Fundamentals
(a) One of the desiderata for an algorithm is that it should be “correct”. Describe in one sentence
what is meant by an “incorrect” algorithm.
[2 marks]
A text document will always be smaller when encoded in UTF-8 than UTF-16.
[4 marks]
(c) What does it mean for an algorithm or method to be dual use? Illustrate with the use of an
example.
[3 marks]
A: Dual use means that the algorithm/method can equally be used for good or ill intent. E.g. autonomous cars,
in terms of improving traffic flows (good) but also potentially causing accidents through biased/faulty models (ill).
14
Question 10: Applications of Computing
(a) What are three issues that must be addressed in an “electronic voting” system?
[6 marks]
A: • crypto security/compromises
• avoid artefacts in UI
• targeted malware
15
[10 marks]
Question 11: URLs and the Web
Complete this HTML page:
<! 1 html>
< 2 xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
< 3 http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>COMP10001: The Final Exam</title>
</head>
<body>
<h1>COMP10001: The Final Exam</h1>
<p>Starring:
<ul>
<li>You</li>
<li>Tim, Nic, Marion, Farah</li>
<li>< 4 src="./images/totoro.gif" alt="Totoro!"/></li>
</ul>
</p>
</ 5 >
</html>
by filling in the numbered blanks based on selecting from among the following candidate strings:
Note that you may use the same string for multiple answers.
(1) A: DOCTYPE
(2) A: html
(3) A: meta
(4) A: img
(5) A: body
16