You are on page 1of 14

CDB7C330-3F24-4FAB-A67B-96E97E112B81

apslO6-final-examination
#389 1of14

%
:--6.
UNIVERSITY OF TORONTO
FACULTY OF APPLIED SCIENCE AND ENGINEERING
APS1o6 FINAL EXAM - APRIL 24th 6:30pm-9:oopm
2 HOURS AND 30 Minutes

INSTRUCTORS: S. Colic, A. Olechowski, D. Rosu, C. Variawa

First name (please write as legibly as possible within the boxes)

Last name

Student ID number

Please write your UTORID here:

**DO NOT REMOVE THE STAPLE**


WRITING ON PAGES WITHOUT A QR-CODE WILL NOT BE GRADED

PLEASE WRITE CLEARLY AND LEGIBLY


Reminders:
If Python code is incorrectly indented, written, or interpreted, it is incorrect.
You should explicitly import any standard modules that you need.
Only faculty-approved calculators are allowed.
No textbooks, notes, or other aids.
Marks will be awarded for correctness of your algorithm, Python syntax, adherence
to recommended Python coding practice, comments, and the clarity of your
program.
Time allotted: 2h 30mm

Question Maximum Mark


1 10
2 10
3 10
4 10
5 10
Total 50

Page 1 of 13
U aps106-final-examination
- #389 2of14

0:
THIS PAGE IS NOT GRADED

Page 2 of 13
5C6389FF-6287-458B-A1AA-8978F2C7FCD2

aps106-final-examination
E1 E1
#389 3 of 14

Question 1. [10 marks] Multiple Choice


-

(Please select the one most-correct answer per question)

*ALL MULTIPLE CHOICE QUESTIONS MUST BE ANSWERED ON THE BUBBLE SHEET


ATTACHED TO THE END OF THIS EXAM PACKAGE**

Q1A) [1 mark] What is the type of the default value returned by a Python function that
does not contain an explicit return statement?

mt
bool
void
NoneType

Qib) [1 mark] If this set of commands is executed in shell, what will be the output?
>>>str="hello"
>>>str [:2]
he
lo
olleh
hello

Qic) [1 mark] Which of the following results in a SyntaxError?


' "Once upon a time... ", she said.'
"He said, 'Yes!'"
C) '3\'
d) "'That's okay'"

Qid) [1 mark] What is the output for the following statement?

>>>print(4/(3*(2_1)) == 4/3*(2_1))

True
False

Qie) [1 mark] What is the output of the following?

x = "abcdef"
± = UI,,
while i in x:
print(i, end=" ")

no output
i i i i i i
a b c d e f
abcdef

Page 3 of 13
Ir%1 Li
F ç aps106-final-examination
#389 4 of 14
Os
Qit) [1 mark] What is the output of the following?

x = ['ab', 'Cd']
for i in x:
i .upper()
print (x)

['ab', 'Cd']
['AB' , 'CD']
[None, None]
none of the above

Qig) [1 mark] What is the output when the following code is executed?

>>>names = ['Anagha', 'Tanishq', 'FruitPunch', 'Gloria']


>>>print (names [-1] [-1])

a
airoiG, hcnuPtiurF
Error
Gloria

Q1h)[1 mark] What type of data is: a=[ (1,1), (2,4), (3,9)]?

Array of tuples
List of tuples
C) Tuples of lists
d) Invalid type

Q1i) [1 mark] Read the code shown below and pick out the keys.

d = ("Running": 45, "Hiking":101, "Biking":29, "Walking": 9000)

45, 101, 29, 9000


"Running", "Hiking", "Biking" and "Walking"
"Running:45", "Hiking:101", "Biking:29" and "Walking:9000"
d = (45, 101, 29, 9000)

Q1j) [1 mark] Which is the most appropriate definition for recursion?

A function that calls another function


A function execution instance that calls another execution
instance of the same function
C) A class method that calls another class method
d) A in-built method that is automatically called

*REMINDER: ALL MULTIPLE CHOICE QUESTIONS MUST BE ANSWERED ON THE BUBBLE SHEET AT THE
END OF THIS EXAM BOOKLET IN ORDER TO BE GRADED*

Page 4 of 13
3FO6EBEO-3DB5-4765-ADB3-FC09A7552AA4

apslO 6-final-examination
ELiJ
#389 50f14
VC

Question 2. [10 marks] Short-answers


-

For the following questions indicate what the code will print or write to a file.
If an error is produced, write down the output printed before the error is encountered, and
then write "Error". Write the answer in the box provided.

[2 marks]
d = 11: [1,2J, 0:[3,4] 1

print(d[1])
print(d[0] .append(5))

print (d[0] [-1])

[2 marks] file: names.txt

names = ['Tina', 'Sue', 'Brad']


myfile = open("names.txt", "w")

for item in names:


myfile .write (item. lower 0)

myfile close ()
.

[2 marks]
def substitute(s):
" (string) -> string"

subs = s
± = len(subs) II 2
while I <= len(subs)
subs[i] = IP
i = i + 2

return sub_s upper ()


.

print (substitute ('hello spring'))

Page 5 of 13
,

aps106-final-examination
#389 6 of 14

d) [2 marks]
def all val(x, val):
""(list, int)->(list)"""

index_len = len(x)
for i in range (index_len)
x[i] = val
return x

z = [1,2,3]
x = z[:]
y = all val(x,2)

print (z)
print (x)
print (y)

e) [2 marks]
def fun2 (1st)
it if if (list)-> (list)

if 1st == []:
return [1
else:
1 = lst[-1]
11 = lst[:-1]
return [1] + fun2(11)

1st = [1, 2, 3, 41

print (fun2 (1st))

Page 6 of 13
C9A408B6-51BC-424C-A665-72170315D26C
. ~g
LI
aps106-final-examination

#389 7 of 14 ~K%x

Question 3 [10 marks total] Build the Code


-

Part (A) [4 marks]:

Write a function named vectorize (M) which takes in M, a list of lists representing a matrix, and
returns a list representing a vector.
2145
5 2 8 1 0, [2 1 4 5 5 2 8 1 3 6 2 01
3620
Example:
>>> M = [[2, 1, 4, 51, [5, 2, 8, 11, [3, 6, 2, 0]]
>>> vectorize(M)
[2, 1, 4, 5, 5, 2, 8, 1, 3, 6, 2, 01

Answer for Q3A: Please start from the function heading below.

def vectorize (M)


(list of lists) —> list
Transforms a two dimensional matrix M into a vector.
oil

Page 7 of 13
11
aps106-final-examination
#389 8 of 14
0•
Part (B) [6 marks]:

Write a function named reshape (V, m, n) which takes in V. a list which represents a vector, and
returns a list of lists representing a matrix reshaped to have m rows and n columns. If the input
vector cannot be reshaped into a matrix of the specified dimensions, then return an empty list
(i.e. []) and print, "Error: vector cannot be reshaped to specified dimensions".

Example:
>>> V = [2, 1, 4, 5, 5, 2, 8, 1, 3, 6, 2, 0]
>>> reshape(V, 2, 6)
[[2, 1, 4, 5, 5, 2], [8, 1, 3, 6, 2, 0]]
>>> reshape(V, 3, 6)
"Error: vector cannot be reshaped to specified dimensions"

Answer for Q3B: Please start from the function heading below.

def reshape(V, m, n)
'''(list, int, int) -> list of lists
Transforms a vector V into a two dimensional matrix with m
rows and n columns. If the vector cannot be reshaped to the
dimensions specified by m and n, then print the error message
'Error: vector cannot be reshaped to specified dimensions' and
return an empty list.
I II

Page 8 of 13
B7D19387-BE30-4320-B19A-92BFB2211756

aps106-final-examination
L1 EEl
-

#389 9 of 14
EEl
Question 4 [10 marks total] Complete the Code
-

The incomplete code below defines a new class of Vehicle objects. Parts A, B and C ask you to
complete the sections of the code in the boxes according to the methods' docstrings. Part D asks
you to write what would be printed by the preceding code.

class Vehicle:
def mit (self, speed, maxSpeed, colour)
self.speed = speed #in km/h
self .maxSpeed = maxSpeed #in km/h
self.colour = colour

def accelerate(self, x):


"'Increases the Vehicle object's speed by x. Note that
the Vehicle cannot have a speed higher than its maxSpeed
attribute.'''
A (3 marks)

def brake (self, x):


self.speed = self.speed - x
if(self.speed < 0)
self.speed = 0

def race(self, other)


'''Returns the Vehicle object self or other, whichever
has a higher speed. In the case of a tie, returns the
self object'''
B (3 marks)

def str (self)


I "'Returns the Vehicle in the form: <colour> vehicle
travelling at <speed> km/h
>>> print(Vehicle(0,100,"red")
red vehicle travelling at 0 km/h
"I

C (2 marks)

red car = Vehicle(60, 200, "red")


blue car = Vehicle(80, 160, "blue")
red car.accelerate (10)
blue—car. brake (5)
print("The winner of the race is",red car.race(blue car))

D (2 marks) What is the output from running the code above?


-

Page 9 of 13
U apslO6-final-examination
#389 10 of 14
0•.
BLANK PAGE FOR ROUGH WORK (NOT GRADED)

Page 10 of 13
E7FD05C3-7FEA-44C3-BFBB-7977F5FC1E05

aps106-final-examination

#389 11 of 14

%
~.-J
Question 5. [10 marks total] Complete the Code
-

Similarly to the examples discussed during lectures, the incomplete code below defines a class of
Node objects and a class of LinkedList objects. Each Node object has the two attributes we saw in
class and an additional third attribute: cargo (of type string), next (of type Node), and priority (of
type integer). An object of type LinkedList is a collection of Node objects that are "linked" to each
other, i.e., each element contains a reference to its successor.

Complete the methods in parts A, B and C according to their docstrings by writing code in the
boxes provided. When writing your code, you can use any of the methods given in the
definition of the LinkedList class.

class Node:

def mit (self, c = None, p = None)


'Creates an object of type Node.'''

self.cargo = c
self.priority = p
self.next = None

class LinkedList:

def mit (self)


'''Create a linked list, i.e., an object of type
LinkedList. This list is empty.
, , ,

self.length = 0 # the number of elements in the list


self.head = None

def insert in front(self, cargo, priority)


(LinkedList) -> NoneType
Insert an element at the front of the list.
, , ,

if self.length == 0:
self.head = Node(cargo, priority)
else:
aux = self.head
self.head = Node(cargo, priority)
self.head.next = aux

self.length += 1

def insert _after_node (self, n, cargo, priority)


(LinkedList) -> NoneType
Insert an element in the list, right after node n.
, , ,

aux = n.next
n.next = Node(c, priority)
n.next.next = aux
self.length += 1

Page 11 of 13
023D032B-F98F-4C54-8858-A4223F94 6946
E1
: aps106-final-examination

#389 12 of 14

0•.
Part (A) [2 marks]
def isempty(self)
(LinkedList) —> bool
Return True if the list is empty and False otherwise.
''V

Part (B) [3 marks]


def extract first (self)
(LinkedList) —> string or NoneType
If the list has at least one element, remove the first
element from the list, return its cargo and assign the
next node in the sequence to be the new head of the list.
If the list has only one element, remove the element and
return its cargo. Return None if the list is empty. (No
element removal is performed in this case.)
III

PART C IS ON THE NEXT PAGE

Page 12 of 13
4B2BF5AO-9973-4CFA-A33A-7D937B1B6758
LI
.
aps106-final-examination
#389 13 of 14
Ev
e a

Part (C) [5 marks]


The elements of this new type of LinkedList are "arranged" in an order consistent with their
priority, i.e., the Node object with the highest priority is at the front of the list and the object with
the lowest priority is at the back of the list. A new element is added to a linked list at a position
that is consistent with its priority relative to the priority of the existing elements. We assume that
there are no objects with the same priority.

For example, assuming that ('Alexis', 3) represents a Node object with cargo 'Alexis' and priority
3, adding ('Alexis', 3) to the list

('Robin', 7) -> ('Erin', 6) - ('Ashley', 1)

would change the list to

('Robin', 7) - ('Erin', 6) 4 ('Alexis', 3) - ('Ashley', 1).

Note that ('Robin', 7) is the first element and ('Ashley', 1) is the last element of the list.

def insert(self, cargo, priority):


(LinkedList, string, int) -> NoneType
I

Insert a new element in the list at the position


corresponding to its given priority.
Update the length of the list.
III

*fJfflJER, AGAIN: ALL MULTIPIECHDICEIIIESTIDNS MUST BE ANSWERED ON THE BUBBLE


SHEET AT THE END OF THIS EXAM BOOKLET IN ORDER TO BE GRADED*

Page 13 of 13
27F69D41-35E3-4E9C-A70C-2A4247E3D28C

aps106-final-examination
#389 14 of 14

0•

I CD CD CD CD CE) 21

2 22 c

3 c c 23

4 IN c 24 c c

5 25 c

6 D 26 CA ic

7 27 c

8 28 D

9 CD c 29 c

10 30

II 31 D

12 32 ©

13 c c cc 33 (I D CD ®

14 34 c

15 c c c 35 c

16 c 36 CE)

17 37

18 c c c 38 c c

19 39 c c c©

20 (A c 40

You might also like