Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

School of Computing and Information Systems

COMP10001 Foundations of Computing

Practice Exam, May 2023

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 on 29 May. 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 (20 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

(b)   2 ** 3 * 3 ** 2

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

(d)   2 * "three"

(e)   max("minimum")

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

(g)    "chromosome".split("o")

(h)   set("green") & set("grass")

(i)   [y>3 for y in range(1, 5)]

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

Question 2 (20 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 you can.  If your answer requires more than one assignment statement you will be eligible for partial marks.

(a)   Suppose that lst is a non-empty Python list. Give a Python assignment statement that assigns True to ends same if the rst 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.

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

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

(e)   Suppose that nums is a list of Python numbers.  Give a Python assignment statement that creates a list cum sums the same length as nums that contains the corresponding cumulative sums formed by adding up prefixes of nums, starting with a prefix of length one, so that if nums has the value [2,  4,  3,  -1], then cum sums will be assigned [2,  6,  9,  8].

Question 3 (15 marks)

The following function searches a set of lines of text to nd 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

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?

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

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

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

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

Question 4 (15 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      strings  that  are  separated by  any  of  the  characters  in delims‘ . If  there  are multiple  consecutive  delimiters  in text‘,  these      should be  treated  as  a  single  delimiter .  If no  delimiters  are      present  in text‘  at  all,  return  a  list  containing  only text‘ .  ’’’

result  =  []                                                                                                  #  02 curr  =  ""                                                                                                      #  03

for  char  in  text:                                                                                      #  04 if  char  in  delims:                                                                             #  05 if  len(curr)  >=  0:                                                                     #  06

result .append(curr)                                                           #  07 curr  =  None                                                                           #  08

else:                                                                                                      #  09 curr  +=  char                                                                                #  10

if  curr  ==  "":                                                                                            #  11 result .add(curr)                                                                                #  12

return  result                                                                                              #  13

Unfortunately, the function contains a number of errors. The subquestions on the next two pages are designed to help you first identify those errors, and then correct them.

(a)    [4 marks] Trace the computation that is performed for the function call

split_any("comp10001",  "2")

to determine what is returned. Show both the value and type in the answer that you provide. Or, if you think an exception will be raised before the function returns, 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).

Now write the output that should have been returned for that input if the function was working correctly.

Finally, 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.

(b)    [4 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).

Now write the output that should have been returned for that input if the function was working correctly.

Finally, 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.

(c)    [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. In answering this part of the question, you should assume that the errors already identified in parts (a) and (b) have been fixed.

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 as a result of this error.

Finally, 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)    [3 marks] Now locate the other error in the function, and briefly describe it in one sentence. You do not need to give a function call that would expose this error.

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

Question 5 (30 marks)

Recall the Matching Game from Assignment 1, which featured a number of colored pieces on a two-dimensional board, with the board represented in Python by a list of lists. Each piece was represented as a string containing a single upper-case character between ’A’ and ’Y’ . The character ’Z’ was used to indicate a blank position on the board.  For example, a board might have four columns and three rows and look like this:

board  =  [[’B’,  ’G’,  ’B’,  ’Y’],

[’G’,  ’B’,  ’Y’,  ’Y’],

[’G’,  ’G’,  ’Y’,  ’Z’]]

In this question you will implement a number of powerups” – functions that manipulate the board in ways that would not normally be permitted by the rules of the game.  You are not required to include comments or docstrings in your functions, but may if you wish.

(a)    [6 marks] Write a Python function

corner_destroyer(board)

that takes one parameter: board, a list of lists representing a game board.  Your function should manipulate the board such that the pieces in the top-left, top-right, bottom-left and bottom-right

positions are replaced by blanks (i.e. character ’Z’).

For example:

>>> board  =  [[’B’,  ’G’,  ’B’],  [’G’,  ’B’,  ’Y’],  [’G’,  ’G’,  ’Y’]] >>>  corner_destroyer(board)

>>> print(board)

>>>  [[’Z’,  ’G’,  ’Z’],  [’G’,  ’B’,  ’Y’],  [’Z’,  ’G’,  ’Z’]]

(b)    [8 marks] Write a Python function

board_combiner(board1, board2)

that takes two parameters:  board1 and board2.  Both parameters are lists of lists representing game boards and both of those two game boards have the same number of rows and columns. Your function should return a new board which contains the columns from board1 interleaved with the columns from board2. For example, if board1 and board2 contained two columns then:

• The rst column of the new board is the rst column of board1;

The second column of the new board is the rst column of board2;

The third column of the new board is the second column of board1;

• The fourth column of the new board is the second column of board2.

For example:

>>> board1  =  [[’A’,  ’A’],  [’C’,  ’C’]]

>>> board2  =  [[’B’,  ’D’],  [’B’,  ’D’]]

>>> new_board  = board_combiner(board1, board2)

>>> print(new_board)

[[’A’,  ’B’,  ’A’,  ’D’],  [’C’,  ’B’,  ’C’,  ’D’]]

(c)    [8 marks] In this modified version of the game, we consider the game to be “won” if there are no more than 3 occurrences of any piece colour on the board. Write a Python function

has_won(board)

that takes one parameter: board, a list of lists representing a game board.  Your function should return True if the game has been won given the current board state and False otherwise.

For example:

>>> board  =  [[’B’,  ’G’,  ’B’],  [’G’,  ’B’,  ’Y’],  [’G’,  ’G’,  ’Y’]] >>> print(has_won(board))

False

>>> board  =  [[’B’,  ’G’,  ’B’],  [’G’,  ’B’,  ’Z’],  [’Z’,  ’Z’,  ’Z’]] >>> print(has_won(board))

True

(d)    [8 marks] We now wish to devise a way of saving the board to a file so that a player may return to the game later. Write two functions:

•  save board(board,  filename) that takes two parameters: board, a list of lists represent- ing a game board; and filename, the name of a file to which the board should be saved. This function should output the board to the le specified by filename in a format that can be loaded using your load board function.

•  load board(filename) that takes a single parameter: filename, the name of a le con- taining the saved board. Your function should return a list of lists representing the board.

For example:

>>> board  =  [[’B’,  ’G’,  ’B’],  [’G’,  ’B’,  ’Y’],  [’G’,  ’G’,  ’Y’]] >>>  save_board(board,  ’savegame .txt’)

>>> board2  =  load_board(’savegame .txt’)

>>> print(board2)

[[’B’,  ’G’,  ’B’],  [’G’,  ’B’,  ’Y’],  [’G’,  ’G’,  ’Y’]]

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.