Exam 2024s1 Practice Solutions
Exam 2024s1 Practice Solutions
Exam 2024s1 Practice Solutions
Instructions to Students: This exam contains 100 marks, and counts for 50% of your final grade.
Be sure to write your student number clearly in all places where it is requested.
This assessment is closed book, and you may not make use of any printed, written, electronic, or
online resources.
All questions should be answered in the spaces provided on the exam paper. There is also an
overflow page available at the end of the paper. If you write any answers there, be sure to also write
the corresponding question number.
There are a number of places where you are asked for a single Python statement, but two or more
answer lines are provided. In these cases you may draft your answer in one line and then copy it
neatly to another line within the answer boxes if you wish, but if you do so you must then cross out
the first draft answer.
You must not communicate with any other student in any way from the moment you enter the exam
venue until after you have left the exam venue. All phones and other network, communication, and
electronic devices must be switched completely off while you are in the exam room.
All material that is submitted as part of this assessment must be completely your own unassisted
work, and undertaken during the time period allocated to the assessment.
Calculators and dictionaries are not permitted.
In your answers you may make use of built-in functions, but may not import functions from any
other libraries.
You may use any blank pages to prepare drafts of answers, but you must copy those answer onto
the correct answer box before the end of the exam.
A solution to this Practice Exam will be made available in the LMS in Week 12. You should allocate
yourself a 120 minute window and try it before then, working under exam consitions. And maybe
even buy yourself a new pen to do it with, so that you know you have a reliable pen to use.
Question 1 (18 marks)
Each subquestion is worth 2 marks. To get full marks you must specify both the correct value and
be clear in your answer that you understand what the type will be. If you think an expression is not
legal according to the rules of Python, you should write “Error” in the box. If you want to include
any blanks in output strings, draw one symbol for each blank character.
(a) 3 * 2 - 11 / 4 3.25
(b) 2 ** 3 * 3 ** 2 72
Each subquestion is worth 4 marks. There are two lines provided for each answer, but you should
give a single Python assignment statement. If your answer uses more than one assignment state-
ment, you will receive 0 marks.
If you wish you may also use the first line to draft your answer before copying it neatly into the
second line. If you choose to do that, be sure to cross the first answer out with a single straight line
so that your single answer line is clear.
(a) Suppose that lst is a non-empty Python list. Give a Python assignment statement that as-
signs True to ends same if the first and last item in lst are the same, and assigns False if not.
(b) Suppose that nums is a non-empty Python list of numbers. Give a Python assignment state-
ment that assigns to averg the average of the numbers in nums.
avrg = sum(nums)/len(nums)
(c) Suppose that n is a non-negative integer. Give a Python assignment statement that assigns to
zzs a list of n strings, where each string is n repetitions of the letter ’z’.
zzs = ["z" * n] * n
(d) Suppose that str1 and str2 are Python strings. Give a Python assignment statement that
assigns to match len the number of initial characters for which str1 and str2 are the same.
The following function searches a set of lines of text to find the ones in which some set of words
all arise, with repeat appearances also possibly required.
retained = [] # 05
include_line = True # 07
# now check the query word freqs against the line freqs
for w in query_d: # 12
XXXXXXXXXX # 13
XXXXXXXXXX # 14
# all lines have been considered, we have the ones that match
return retained # 17
for w in words:
retained.append(line)
Consider the following Python function. The function is designed to split some text into a list of
strings, where splits are performed whenever any of the characters in delims are encountered.
if result[-1].strip() != "": # 10
result.append(curr.strip()) # 11
return result # 12
Unfortunately, the function contains a few errors. The following subquestions are designed to help
you first identify these errors, and then correct them.
(a) [2 marks] Trace the computation that is performed for the function call
split_any("a,b,c", ",")
to determine what is returned. Write both the return value and its type, or, if you think an exception
will be raised, indicate in English what error will arise (for example, “divide by zero”, or “index
out of range”, or “invalid method for type int”, and so on).
[’ab’, ’c’]
Now write the output that should have been returned for that input if the function was working
correctly.
split_any("1+8-3=6", "-+=")
to determine what is returned (or, if the function does not return, describe the error that occurs),
providing the same details required in part (a).
[’18’, ’36’]
Now write the output that should have been returned for that input if the function was working
correctly.
(c) [2 marks] One error was responsible for the undesired behaviour revealed in parts (a) and (b).
Identify a minimal fix for this error, by giving exactly one line number in the code that is to change,
and then providing one replacement line that corrects the error.
(d) [4 marks] There are two further errors present in the function that are not revealed by the tests
shown in parts (a) and (b) of this question.
Write a function call that would expose one of these other two errors (you may choose either).
Describe what the result of that function call should be, and what it would actually be.
Identify a minimal fix for this error, by giving exactly one line number in the code that is to change,
and then providing one replacement line that corrects the error.
Now briefly describe the other error in the function in one sentence.
Trailing/leading whitespace is not stripped from strings prior to the last element
Recall the Zoomerbinis from Assignment 2. There were 256 different possible “types” of Zoomerbi-
nis, derived from the various combinations of four attributes. Below are some definitions which
capture three of the same four attributes and their possible values in an abbreviated form:
ATTRS_VALUES = {
ATTRS[0]: ["wav", "cur", "cap", "bea"],
ATTRS[1]: ["red", "blu", "yel", "gre"],
ATTRS[2]: ["tik", "sna", "dis", "ins"]
}
Note: You may assume these definitions are available in the global scope in your responses (you
do not need to re-define them). They should be treated as constants and never modified.
In the following problems, a Zoomerbini is represented as a tuple of strings indicating their attribute
values, following the order of ATTRS. For example, if using the above definitions, a Zoomerbini
with wavy hair, red as their favourite colour, and TikTok as their social media platform would be
represented as: ("wav", "red", "tik").
To be eligible for full marks in this question, your code must be correct even if the ATTRS and
ATTRS VALUES definitions were changed. Where necessary, you should use these constants directly
rather than “hardcode” specific values. You may assume that:
• ATTRS will be a non-empty list of strings, and ATTRS VALUES will be a dictionary containing
string keys (matching the strings in ATTRS) and non-empty lists of strings as values. Each list
of strings denotes the possible values for each attribute.
• Strings within each attribute value list will always be different to each other, but the same
string could potentially appear in multiple value lists.
• Inputs to your functions will always be consistent with ATTRS and ATTRS VALUES, that is,
Zoomerbinis will be represented as tuples of strings following the number and order of at-
tributes in ATTRS, with values selected from the lists in ATTRS VALUES.
You may (optionally) use standard Python library functions in your answers, but if you do, you must
include corresponding import statement(s) in every answer where you use them. Additionally, if
you choose to define any constants of your own (constants aside from those provided above), you
must explicitly redefine these in every part where they are used. You are not required to include
comments or docstrings in your functions, but may if you wish.
similarity(zbini1, zbini2)
that takes two parameters: zbini1, a Zoomerbini tuple; and zbini2, another Zoomerbini tuple of
the same length.
Your function should return a non-negative integer denoting the number of attributes that have the
same value in both Zoomerbinis.
Here are two possible execution sequences:
missing_values(zbinis, attr)
that takes two parameters: zbinis, a list of Zoomerbini tuples (all of the same length); attr, a
string representing an attribute (one of the strings in the ATTRS list).
Your function should return a list of the values that are missing from the given attribute across
all Zoomerbinis in zbinis. The same value should not appear more than once in the returned
list, and the order should follow that with which they appear in the respective values list (in the
ATTRS VALUES dictionary).
Here are two possible execution sequences:
>>> zbinis = [
... ("wav", "red", "dis"),
... ("cap", "blu", "dis"),
... ("cap", "gre", "tik"),
... ("bea", "yel", "tik")
... ]
>>> missing_values(zbinis, "hair")
["cur"]
>>> missing_values(zbinis, "social")
["sna", "ins"]
that takes three parameters: zbinis, a list of Zoomerbini tuples (all of the same length); attr, a
string representing an attribute (one of the strings in the ATTRS list); and amount, a positive integer.
Your function should return a new list of Zoomerbini tuples, where the values for the given attribute
across all Zoomerbinis in zbinis have been shifted “forward” by amount. That is, for the i-th
Zoomerbini, the (i + amount)-th Zoomerbini in the returned list should have the respective value
for the given attribute. Value(s) that are shifted off the end of the list should wrap around to the
beginning of the list.
Here are two possible execution sequences:
>>> zbinis = [
... ("wav", "red", "tik"),
... ("cur", "gre", "tik"),
... ("cap", "blu", "sna"),
... ]
>>> rotate_attr(zbinis, "hair", 1)
[("cap", "red", "tik"), ("wav", "gre", "tik"), ("cur", "blu", "sna")]
>>> rotate_attr(zbinis, "social", 2)
[("wav", "red", "tik"), ("cur", "gre", "sna"), ("cap", "blu", "tik")]
result = []
for i in range(len(zbinis)):
zbini = list(zbinis[i])
zbini[attr_idx] = zbinis[(i - amount) % len(zbinis)][attr_idx]
result.append(tuple(zbini))
return result
• save zbinis(zbinis, filename) that takes two parameters: zbini, a list of Zoomerbini
tuples (all of the same length); and filename, the name of a file to which they should be
saved. This function should output the Zoomerbinis to the file specified by filename in a
format that can be loaded using your load board function.
• load zbinis(filename) that takes one parameter: filename, the name of a file from
which to load Zoomerbinis. This function should return a list of Zoomerbini tuples that
were saved to the file specified by filename.
For example:
def load_zbinis(filename):
zbinis = []
with open(filename) as file:
for line in file:
zbinis.append(tuple(line.strip().split()))
return zbinis
(a) [4 marks] What does it mean for an algorithm or method to be dual use? Illustrate with the
use of an example.
Dual Use - the algorithm or method can be used for both good and malicious purposes. One
example is generative AI, where technology that can be used to identify potential cures to
diseases can also be to develop new chemical / biological weapons.
(b) [4 marks] Tom claims that a text document will always be smaller when encoded in UTF-8
than UTF-16. Is Tom correct? Why or why not?
No, Tom is not correct. Although the vast majority of documents will be smaller in UTF-8 than
UTF-16, there are some characters that require two bytes to represent in UTF-16 and three to
represent in UTF-8. This is because UTF-8 allows characters to be encoded using 1, 2, 3 or
4 bytes, while UTF-16 allows only 2 or 4 bytes. More bits are therefore required to represent
the number of bytes used to encode the character. A document made up mainly of characters
that fit into two bytes in UTF-16 but require three in UTF-8 would be larger when encoded in
UTF-8.
(c) [3 marks] One of the desiderata for an algorithm is that it should be “correct”. Describe in
one sentence what is meant by an “incorrect” algorithm
An incorrect algorithm is one that can either: (a) terminate with the wrong output; or (b) not
terminate for some input.