[go: up one dir, main page]

0% found this document useful (0 votes)
12 views14 pages

Exam 2024s1 Practice Solutions

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

School of Computing and Information Systems

COMP10001 Foundations of Computing

Practice Exam, May 2024

Time Allowed: Two hours.

Reading Time: Fifteen minutes.

Authorized Materials: None.

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

(c) [1, 3, 4, 6][2: 4] * 2 [4, 6, 4, 6]

(d) 2 * "three" ”threethree”

(e) max("minimum") ”u”

(f) "[1, 3, 8]"[::-1] ”]8 ,3 ,1[”

(g) set("green") & set("grass") {”r”, ”g”} (either order permitted)

(h) [y>3 for y in range(1, 5)] [False, False, False, True]

(i) 3 * (True or True and "5") 3

COMP10001 Practice Exam Page 1 of 13 Turn The Page


Question 2 (16 marks)

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.

ends same = lst[0] == lst[-1]

(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.

match len = sum([str1[0:k]==str2[0:k] for k in range(1, 1+len(str2))])

COMP10001 Practice Exam Page 2 of 13 Turn The Page


Question 3 (15 marks)

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.

def word_finder(lines, words): # 01


’’’
Processes a set of ‘lines‘ to retain only the ones that contain
each word in a set of ‘words‘ that are given as a query. If a
word appears multiple times in the query, it must appear at least
that many times in any retained lines. Word comparisons are
case-insensitive.
’’’

# first build a dictionary for the query words


query_d = {w.lower(): 0 for w in words} # 02
XXXXXXXXXX # 03
query_d[w.lower()] += 1 # 04

retained = [] # 05

# then process the input lines one at a time


for line in lines: # 06

include_line = True # 07

# build a dictionary for this line


XXXXXXXXXX # 08
line_d = {w.lower(): 0 for w in line_words} # 09
for w in line_words: # 10
line_d[w.lower()] += 1 # 11

# now check the query word freqs against the line freqs
for w in query_d: # 12
XXXXXXXXXX # 13
XXXXXXXXXX # 14

# and add to the output lines if passed that test


if include_line: # 15
XXXXXXXXXX # 16

# all lines have been considered, we have the ones that match
return retained # 17

COMP10001 Practice Exam Page 3 of 13 Turn The Page


There are five locations in the function where one line of Python code has been replaced by XXXX
symbols. The number of X’s should not be used as an indication of the length of the text that has
been covered up.
In the boxes below, write the Python statement that has been covered up at each of the named
locations. Each subquestion is worth 3 marks.

(a) What has been covered up at line 03?

for w in words:

(b) What has been covered up at line 08?

line words = line.split()

(c) What has been covered up at line 13?

if w not in line d or query d[w] > line d[w]:

(d) What has been covered up at line 14?

include line = False

(e) What has been covered up at line 16?

retained.append(line)

COMP10001 Practice Exam Page 4 of 13 Turn The Page


Question 4 (10 marks)

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.

def split_any(text, delims): # 01


’’’
Given a string ‘text‘ and a string ‘delims‘, return a list of
non-empty strings that are separated by any of the characters
in ‘delims‘. If ‘text‘ does not contain any ‘delims‘, return
a list containing just ‘text‘. Trailing and leading whitespace
should be omitted from each string in the list of results.
’’’
result = [] # 02
curr = "" # 03

for char in text: # 04


if char not in delims: # 05
curr += char # 06
elif len(curr.strip()) > 1: # 07
result.append(curr) # 08
curr = "" # 09

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.

[’a’, ’b’, ’c’]

COMP10001 Practice Exam Page 5 of 13 Turn The Page


(b) [2 marks] Next, trace the function call

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.

[’1’, ’8’, ’3’, ’6’]

(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.

Line 07: elif curr.strip():

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

split any("a,b,c", "?")

Describe what the result of that function call should be, and what it would actually be.

Should be: [’abc’]. Actually: IndexError

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.

Line 10: if curr.strip():

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

COMP10001 Practice Exam Page 6 of 13 Turn The Page


Question 5 (30 marks)

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 = ["hair", "colour", "social"]

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.

Question 5 continues on the following pages.

COMP10001 Practice Exam Page 7 of 13 Turn The Page


(a) [6 marks] Write a Python function

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:

>>> similarity(("wav", "red", "tik"), ("wav", "gre", "tik"))


2
>>> similarity(("wav", "red", "tik"), ("cur", "gre", "sna"))
0

def similarity(zbini1, zbini2):


count = 0
for attr1, attr2 in zip(zbini1, zbini2):
if attr1 == attr2:
count += 1
return count

(b) [8 marks] Now write a Python function

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"]

COMP10001 Practice Exam Page 8 of 13 Turn The Page


def missing_values(zbinis, attr):
attr_idx = ATTRS.index(attr)
values = [v for v in ATTRS_VALUES[attr]]
for zbini in zbinis:
if zbini[attr_idx] in values:
values.remove(zbini[attr_idx])
return values

(c) [8 marks] Now write a Python function

rotate_attr(zbinis, attr, amount)

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

def rotate_attr(zbinis, attr, amount):


attr_idx = ATTRS.index(attr)

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

COMP10001 Practice Exam Page 9 of 13 Turn The Page


[8 marks] We now wish to devise a way of saving a list of Zoomerbinis to a file so that they can
be loaded back into the exact same list of Zoomerbinis at some point in the future. Write two
functions:

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

>>> zbinis = [("wav", "red", "tik"), ("cur", "gre", "tik")]


>>> save_zbinis(zbinis, "two_zbinis.txt")
>>> zbinis2 = load_zbinis("two_zbinis.txt")
>>> zbinis2
[("wav", "red", "tik"), ("cur", "gre", "tik")]

def load_zbinis(filename):
zbinis = []
with open(filename) as file:
for line in file:
zbinis.append(tuple(line.strip().split()))
return zbinis

def save_zbinis(zbinis, filename):


with open(filename, "w") as file:
for zbini in zbinis:
file.write(" ".join(zbini) + "\n")

COMP10001 Practice Exam Page 10 of 13 Turn The Page


Question 6 (11 marks)

(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.

End of Practice Exam, No More Questions

COMP10001 Practice Exam Page 11 of 13


You may use this page for overflow answers to any question. If you use this page be sure that you
mark very clearly which question you are referring to. If you use this page for question drafts that
you do not want to be marked, make sure that you cross them out.

COMP10001 Practice Exam Page 12 of 13


COMP10001 Practice Exam Page 13 of 13

You might also like