0% found this document useful (0 votes)
19 views

Fall 2019 Midterm Solution

This document provides sample solutions to a midterm test for an Introduction to Computer Programming course at the University of Toronto. The midterm test had 6 multiple choice questions covering topics like functions, strings, loops, and boolean expressions. For each question, the document lists the question prompt and possible answer choices. It then provides the correct answer selections. It also includes 3 additional questions testing concepts like functions, constants, and strings, with sample code solutions provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Fall 2019 Midterm Solution

This document provides sample solutions to a midterm test for an Introduction to Computer Programming course at the University of Toronto. The midterm test had 6 multiple choice questions covering topics like functions, strings, loops, and boolean expressions. For each question, the document lists the question prompt and possible answer choices. It then provides the correct answer selections. It also includes 3 additional questions testing concepts like functions, constants, and strings, with sample code solutions provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

lOMoARcPSD|28186506

fall 2019 midterm solution

Introduction to Computer Programming (University of Toronto)

Studeersnel wordt niet gesponsord of ondersteund door een hogeschool of universiteit


Gedownload door Camila Calderon Cruz ([email protected])
lOMoARcPSD|28186506

Midterm Test—Sample Solutions


CSC108H1F / LEC0101/0102
Question 1. [6
October 16 2019, marks]— Duration: 75 minutes
10:10am
This question has six parts. For each question on the left-hand side, circle the letter(s) in front of the corresponding
answer(s) on the right-hand side.
Circle the best docstring description for the function below (A) Doubles the value of num.
according to the Function Design Recipe: (B) Doubles the number.
(C) Return the number multiplied by two.
def double(num: int) -> int:
return num * 2 (D) Return num doubled.

Circle the answer that best describes what is printed when the (A) <class ‘list’>
following code is run: (B) <class ‘int’>
(C) <class ‘str’>
s = ‘Oct’
s = s + ‘31’ (D) <class ‘float’>
print(type(s[4])) (E) <class ‘NoneType’>
(F) Nothing is printed because an error occurs
(G) No error occurs, and something else is printed

Circle all of the code snippets that would print rat if (A) print(s[1:3])
(B) print(s[-2] + s[2] + s[1])
s = ‘stars’
(C) print(s[3:0:-1])
(D) print(s[-2:-5:1])
(E) print(s[::-1])
(F) None of the above will print rat

Circle all of the answers that correctly describe what is printed (A) The first number printed is 4
when the following code is run: (B) The first number printed is 9
(C) There are four numbers printed in total
i = 4
(D) There are sixteen numbers printed in total
while i < 20:
(E) The number 15 is printed
print(i) (F) None of the above correctly describe what is printed
i = i + 5

Circle all of the expressions that would evaluate to True: (A) ‘o’ in [‘Welcome’, ‘to’, ‘CSC108’]
(B) len(‘what\’s’) in [2, 4, 6, 8]
(C) [1, 2, 3, 4, 5] in len(‘hello’)
(D) ‘g’ in (‘abc’ + ‘defg’)
(E) ‘aabbcc’ == ‘abc’ * 2
(F) None of the expressions evaluate to True

Circle all of the code snippets that would result in variable f (A) f = 24 (C) f = 12
referring to the int value 12 and variable g referring to the g = 9 g = 3
int value 2. g = f // g if g >= f:
f = f // g f = g
if g < f:
g = g - 1
(B) f = 24
g = 12
g = f / g (D) f = 12 // 2 + 2
f = f / g g = 16
g = g // f

Solution:
1. D 2. C 3. B, C 4. A, C 5. B, D 6. A, C

Gedownload door Camila Calderon Cruz ([email protected])


lOMoARcPSD|28186506

Midterm Test—Sample Solutions


CSC108H1F / LEC0101/0102

October 16 2019, 10:10am — Duration: 75 minutes

Question 2. [3 marks]
Part (a) [2 marks]
Consider the problem of writing function are_consecutive_nums that has the following docstring description:

"""Return True if and only if i, j and k are consecutive numbers in ascending order.

>>> are_consecutive_nums(4, 5, 6)
True
>>> are_consecutive_nums(3, 2, 1)
False
>>> are_consecutive_nums(3, 3, 4)
False
"""

Several solution attempts are given below. Some are correct and some are incorrect.
Circle the letter in front of each solution attempt that correctly implements the function.

(A) def are_consecutive_nums(i: int, j: int, k: int) -> bool:


if i + 1 == j:
if j + 1 == k:
return True
return False

(B) def are_consecutive_nums(i: int, j: int, k: int) -> bool:


if i == j - 1:
return True
elif j == k - 1:
return True
else:
return False

(C) def are_consecutive_nums(i: int, j: int, k: int) -> bool:


if i + 1 == j or j + 1 == k:
return True
else:
return False

(D) def are_consecutive_nums(i: int, j: int, k: int) -> bool:


if i + 1 != j:
return False
elif j + 1 != k:
return False
else:
return True

Solution: A and D.
Part (b) [1 mark]
Fill in the box below to correctly implement function are_consecutive_nums using a single return statement.
Sample solution:
def are_consecutive_nums(i: int, j: int, k: int) -> bool:

return
i == j - 1 and j == k - 1 # Another solution: i + 1 == j and j + 1 == k

Gedownload door Camila Calderon Cruz ([email protected])


lOMoARcPSD|28186506

Midterm Test—Sample Solutions


CSC108H1F / LEC0101/0102

October 16 2019, 10:10am — Duration: 75 minutes

Question 3. [4 marks]
Complete the following function according to its docstring. You must use the constant VOWELS in your solution.

VOWELS = ‘aeiou’

def get_lowercase_vowels(s: str) -> str:


"""Return a new string with all characters in s that are also in VOWELS, or
an empty string if there are no lowercase vowels in s.

>>> get_lowercase_vowels(‘aardvark’)
‘aaa’
>>> get_lowercase_vowels(‘TWO camels!’)
‘ae’
>>> get_lowercase_vowels(‘123xyzABC’)
‘’
"""

Sample solutions:

# Possible solution:
vowels = ‘’

for ch in s:
if ch in VOWELS:
vowels = vowels + ch # Alternative: vowels += ch

return vowels

# Another possible solution:


vowels = ‘’

for i in range(len(s)):
if s[i] in VOWELS:
vowels = vowels + s[i] # Alternative: vowels += s[i]

return vowels

Gedownload door Camila Calderon Cruz ([email protected])


lOMoARcPSD|28186506

Midterm Test—Sample Solutions


CSC108H1F / LEC0101/0102

October 16 2019, 10:10am — Duration: 75 minutes

Question 4. [4 marks]
Fill in the boxes below to correctly complete the body of function get_sum_matches according to its docstring.
Do not change the code outside of the boxes.

def get_sum_matches(lst: List[int]) -> List[int]:


"""Return a new list that contains each item in lst that is equal to the sum
of the items on either side of it in lst. The first and last items of lst
must not be included because they do not have items on both sides.

Precondition: len(lst) >= 3

>>> get_sum_matches([5, 6, 1, -5])


[6, 1]
>>> get_sum_matches([5, 11, 6, -5, 2, 6])
[11, 6]
>>> get_sum_matches([5, 6, 6, 5])
[]
"""

Sample solutions:

# Possible solution
matches = []
for i in range(1, len(lst) - 1): # don’t loop over first and last indexes
if lst[i - 1] + lst[i + 1] == lst[i]:
matches.append(lst[i]) # matches.extend([lst[i]])
# matches = matches + [lst[i]]
return matches

# Another possible solution


matches = []
for i in range(len(lst)): # loop over all indexes, and
# then check if i is not at beginning/end
if 1 <= i <= len(lst) - 1 and lst[i - 1] + lst[i + 1] == lst[i]:
matches.append(lst[i]) # matches.extend([lst[i]])
# matches = matches + [lst[i]]

return matches

Gedownload door Camila Calderon Cruz ([email protected])


lOMoARcPSD|28186506

Midterm Test—Sample Solutions


CSC108H1F / LEC0101/0102

October 16 2019, 10:10am — Duration: 75 minutes

Question 5. [4 marks]
Part (a) [2 marks]
Fill in the box with the while loop condition required for the function to work as described in the docstring. Do not
change the code outside of the box.

def find_index_of_last_digit(s: str) -> int:


"""Return the index of the last occurrence of a digit in s or -1 if s contains no digits.

>>> find_index_of_last_digit(‘csc108’)
5
>>> find_index_of_last_digit(‘801csc’)
2
>>> find_index_of_last_digit(‘Comp Sci’)
-1
"""
i = len(s) - 1

while i >= 0 and not s[i].isdigit(): # s[i] in ’0123456789’, s[i].isdecimal() :


i = i - 1
return i

Part (b) [2 marks]


Fill in the two boxes below to correctly implement the following function. Do not change the code outside of the
boxes. Your code must call find_index_of_last_digit from Part (a).

def find_index_of_first_digit(s: str) -> int:


"""Return the index of the first occurrence of a digit in s or len(s) if s contains
no digits.

>>> find_index_of_first_digit(‘csc108’)
3
>>> find_index_of_first_digit(‘801csc’)
0
>>> find_index_of_first_digit(‘Comp Sci’)
8
"""

reversed_s = s[::-1] *OR* s[-1::-1] *OR* s[:-len(s)-1:-1] *OR* s[len(s)::-1]


return len(s) - 1 - find_index_of_last_digit(reversed_s)

Gedownload door Camila Calderon Cruz ([email protected])


lOMoARcPSD|28186506

Midterm Test—Sample Solutions


CSC108H1F / LEC0101/0102

October 16 2019, 10:10am — Duration: 75 minutes

Question 6. [4 marks]
Complete the following function according to its docstring. You must use the constant PUNCTUATION in your
solution.

PUNCTUATION = ‘?!.,’

def is_punctuated_tweet_word(s: str) -> bool:


"""Return True if and only if s is a valid tweet word followed by
exactly one character in PUNCTUATION. A valid tweet word contains only
alphanumeric characters and underscores. Also, a valid tweet word contains
at least one alphanumeric character.

Precondition: len(s) >= 1

>>> is_punctuated_tweet_word("hello_world!")
True
>>> is_punctuated_tweet_word("WeTheNorth!")
True
>>> is_punctuated_tweet_word("how?are?you?")
False
>>> is_punctuated_tweet_word("Yes!!!")
False
"""

Sample solution:
if not (s[-1] in PUNCTUATION):
return False

alnum_count = 0 # need to make sure there is at least one alphanumeric char in s

for char in s[:-1]:


if char.isalnum():
alnum_count = alnum_count + 1
elif char != ‘_’:
# Valid tweet words can only contain _ or alphanumeric characters.
return False

return alnum_count > 0

Gedownload door Camila Calderon Cruz ([email protected])


lOMoARcPSD|28186506

Midterm Test—Sample Solutions


CSC108H1F / LEC0101/0102

October 16 2019, 10:10am — Duration: 75 minutes

Use the space on this “blank” page for scratch work, or for any solution that did not fit elsewhere.
Clearly label each such solution with the appropriate question and part number.

Total
Gedownload door Camila Marks
Calderon Cruz=([email protected])
25

You might also like