108 Final
108 Final
IN
UNIVERSITY OF TORONTO
EA
Faculty of Arts and Science
D
N
SE
A
DECEMBER 2017 EXAMINATIONS
H
H
SE
A
CSC 108 H1F
N
EA
Instructor(s): Campbell, Fairgrieve,
D and Smith
PL
IN Duration—3 hours
No Aids Allowed
You must earn at least 28 out of 70 marks (40%) on this final examination in order to
pass the course. Otherwise, your final course grade will be no higher than 47%.
Do not turn this page until you have received the signal to start.
In the meantime, please read the instructions below carefully.
Marking Guide
# 1: / 6
This Final Examination paper consists of 12 questions on 21
# 2: / 4
pages (including this one), printed on both sides of the paper. When
you receive the signal to start, please make sure that your copy of # 3: / 6
the paper is complete and fill in your Student Number, UTORid and
Name above. # 4: / 4
# 12: / 8
TOTAL: /70
Question 1. [6 marks]
Each of the following sets of Python statements will result in an error when the code is run. In the table
below, briefly explain why each error occurs.
st_to_line = {'Chester': 2,
'Davisville': 1,
'Union': 1}
if st_to_line['Dundas'] == 1:
print('Yonge-University')
i = 0
lines = [1, 2, 3, 4]
while lines[i] != 5 and i < len(lines):
print(lines[i])
i = i + 1
f.read()
f.readline()[0]
Page 2 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
Question 2. [4 marks]
Fill in the boxes with the while loop condition and the while loop body required for the function to work as
described in its docstring. See the bottom of this page for examples.
while :
-----------------------------------------------------------------------------------
>>> get_and_verify_password('csc108!')
Enter your password: csc108!
True
>>>
>>> get_and_verify_password('^S33kReT')
Enter your password: chairman
Enter your password: ^S33kReT
True
>>>
>>> get_and_verify_password('csc108!')
Enter your password: CSC
Enter your password: 108
Enter your password: IDoNotKnow
False
>>>
Question 3. [6 marks]
In this question, you are to write code that uses a Python dictionary where each key represents the name of
a meal (e.g., 'stew', 'eggs') and the associated value represents a list of table numbers (e.g., 1, 2, 3),
with one list item for each meal order. If there are, for example, three orders for 'stew' at table 2, then 2
will appear three times in the list of table numbers associated with 'stew'.
Part (a) [3 marks] Complete the following function according to its docstring.
def get_num_orders(meal_to_tables: Dict[str, List[int]], meal: str) -> int:
"""Return the number of orders for meal in meal_to_tables.
Part (b) [3 marks] Complete the following function according to its docstring.
def order_meal(meal_to_tables: Dict[str, List[int]], meal: str, table: int) -> None:
"""Modify meal_to_tables to include a new order for meal at table. Place
table at the end of the list of table number(s) associated with meal.
>>> m_to_t = {}
>>> order_meal(m_to_t, 'stew', 4)
>>> m_to_t == {'stew': [4]}
True
>>> order_meal(m_to_t, 'stew', 1)
>>> m_to_t == {'stew': [4, 1]}
True
>>> order_meal(m_to_t, 'eggs', 6)
>>> m_to_t == {'stew': [4, 1], 'eggs': [6]}
True
"""
Page 4 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
Question 4. [4 marks]
Complete the following function according to its docstring.
Question 5. [4 marks]
The docstring below is correct. However, the code in the function body contains one or more bugs. As a
result the function does not work as specified in the docstring.
Page 6 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
Question 6. [6 marks]
In each of the following, circle the best answer that follows directly below the question.
Part (a) [1 mark] If you were searching a sorted list of one million unique items for a particular
value, and the value being searched for was the second item in the sorted list, which algorithm would take
the least time?
Part (b) [1 mark] If you were searching a sorted list of one million unique items for a particular
value, and the value being searched for was not in the sorted list, which algorithm would take the least
time to discover that it was not in the list?
Part (c) [1 mark] If you had an unsorted list of one million unique items, and knew that you would
only search it once for a value, which of the following algorithms would be the fastest?
Part (d) [1 mark] Our sorting code completes all passes of the algorithm, even if the list becomes sorted
before the last pass. After how many passes of the bubble sort algorithm on the list [ 3, 1, 6, 4, 9, 8 ]
could we stop because the list has become sorted?
1 3 5 7
Part (e) [1 mark] Our sorting code completes all passes of the algorithm, even if the list becomes sorted be-
fore the last pass. After how many passes of the insertion sort algorithm on the list [ 9, 8, 3, 1, 6, 4 ]
could we stop because the list has become sorted?
1 2 6 9
Part (f) [1 mark] Our sorting code completes all passes of the algorithm, even if the list becomes sorted be-
fore the last pass. After how many passes of the selection sort algorithm on the list [ 9, 8, 6, 4, 3, 1 ]
could we stop because the list has become sorted?
1 3 5 7
Question 7. [6 marks]
Complete the following function according to its docstring.
Page 8 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
Question 8. [3 marks]
Fill in the boxes to complete the docstring examples for the function below.
>>> dict2 =
"""
for key in D:
index = L.index(key)
L[index] = D[key]
Question 9. [5 marks]
Part (a) [4 marks] The docstring below is correct. However, the code in the function body contains
one or more bugs. As a result the function does not work as specified in the docstring.
Complete the unittest code below so that: (1) the assertions both fail when the buggy function body
given above is used, and (2) the assertions both pass when a function body that correctly implements the
function as described in its docstring is used. Both arguments must have the correct type. Assume that the
is_valid_word function has been correctly imported and may be called as written below.
class TestIsValidWord(unittest.TestCase):
def test_case1(self):
potential_word =
word_list =
actual = is_valid_word(potential_word, word_list)
expected = False
self.assertEqual(actual, expected)
def test_case2(self):
potential_word =
word_list =
actual = is_valid_word(potential_word, word_list)
expected = True
self.assertEqual(actual, expected)
Part (b) [1 mark] Circle the term below that best describes the number of times the loop iterates
when the buggy version of the is_valid_word function given in Part (a) is called.
Page 10 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
Complete the function build_dictionaries according to the example above and its docstring below.
Assume the given file has the correct format.
Page 12 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
def get_distance(lat1: float, long1: float, lat2: float, long2: float) -> float:
"""Return the distance between the location at lat1 and long1 and
the location at lat2 and long2.
"""
>>> id_to_location = {3: [40.8, -73.97], 4: [43.6, -79.4], 11: [51.5, -0.1]}
>>> id_to_name = {3: 'Grand Central', 4: 'Union', 11: 'Blackfriars'}
>>> get_closest_station(43.5, -79.6, id_to_location, id_to_name)
'Union'
"""
class Table()
| Information about a table.
|
| Methods defined here:
|
| __init__(self, table_id: int, num_seats: int, num_occupied: int) -> None
| Initialize a new table with table ID table_id, num_seats seats, and
| num_occupied seats occupied.
|
| >>> table1 = Table(1, 4, 0)
| >>> table1.id
| 1
| >>> table1.num_seats
| 4
| >>> table1.num_occupied
| 0
|
| __str__(self) -> str
| Return a string representation of this table.
|
| >>> table4 = Table(4, 6, 3)
| >>> str(table4)
| 'Table 4: 3 of 6 seats occupied'
|
| set_occupancy(self, num_occupied: int) -> None
| Set the number of seats occupied at this table to num_occupied.
|
| Precondition: self.num_seats >= num_occupied
|
| >>> table1 = Table(1, 4, 0)
| >>> table1.num_occupied
| 0
| >>> table1.set_occupancy(3)
| >>> table1.num_occupied
| 3
Page 14 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
class Restaurant:
"""Information about a Restaurant."""
Part (a) [1 mark] Complete the body of this class Restaurant method according to its docstring.
Part (b) [3 marks] Complete the body of this class Restaurant method according to its docstring. Use
class Table when possible.
Page 16 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
Page 18 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017
__builtins__:
input([prompt: str]) -> str
Read a string from standard input. The trailing newline is stripped. The prompt string,
if given, is printed without a trailing newline before reading.
abs(x: float) -> float
Return the absolute value of x.
chr(i: str) -> Unicode character
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
float(x: object) -> float
Convert x to a floating point number, if possible.
int(x: object) -> int
Convert x to an integer, if possible. A floating point argument will be truncated
towards zero.
len(x: object) -> int
Return the length of the list, tuple, dict, or string x.
max(iterable: object) -> object
max(a, b, c, ...) -> object
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
min(iterable: object) -> object
min(a, b, c, ...) -> object
With a single iterable argument, return its smallest item.
With two or more arguments, return the smallest argument.
open(name: str[, mode: str]) -> TextIO
Open a file. Legal modes are "r" (read) (default), "w" (write), and "a" (append).
ord(c: str) -> int
Return the integer ordinal of a one-character string.
print(value: object, ..., sep=' ', end='\n') -> None
Prints the values. Optional keyword arguments:
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
range([start: int], stop: int, [step: int]) -> list-like-object of int
Return the integers starting with start and ending with stop - 1 (positive step)
or stop + 1 (negative step), with step specifying the amount to increment (or decrement).
If start is not specified, the list starts at 0. If step is not specified,
the values are incremented by 1.
dict:
D[k] --> object
Produce the value associated with the key k in D.
del D[k]
Remove D[k] from D.
k in D --> bool
Produce True if k is a key in D and False otherwise.
D.get(k: object) -> object
Return D[k] if k in D, otherwise return None.
D.keys() -> list-like-object of object
Return the keys of D.
D.values() -> list-like-object of object
Return the values associated with the keys of D.
D.items() -> list-like-object of Tuple[object, object]
Return the (key, value) pairs of D, as 2-tuples.
list:
x in L --> bool
Produce True if x is in L and False otherwise.
L.append(x: object) -> None
Append x to the end of the list L.
L.extend(iterable: object) -> None
Extend list L by appending elements from the iterable. Strings and lists are
iterables whose elements are characters and list items respectively.
L.index(value: object) -> int
Return the lowest index of value in L, but raises an exception if value does
not occur in S.
L.insert(index: int, x: object) -> None
Insert x at position index.
L.pop([index: int]) -> object
Remove and return item at index (default last).
L.remove(value: object) -> None
Remove the first occurrence of value from L.
L.reverse() -> None
Reverse the list *IN PLACE*.
L.sort() -> None
Sort the list in ascending order *IN PLACE*.
str:
x in s --> bool
Produce True if x is in s and False otherwise.
str(x: object) -> str
Convert an object into its string representation, if possible.
S.count(sub: str[, start: int[, end: int]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are interpreted
as in slice notation.
S.endswith(S2: str) -> bool
Return True if and only if S ends with S2.
S.find(sub: str[, i: int]) -> int
Return the lowest index in S (starting at S[i], if i is given) where the
string sub is found or -1 if sub does not occur in S.
S.index(sub: str) -> int
Like find but raises an exception if sub does not occur in S.
Page 20 of 21 cont’d. . .
CSC 108 H1F Final Examination December 2017