# Cmpt113MidtermSolutions

```Name:
NSID:
Marks: 63
Student #:
Department of Computer Science
CMPT 113.3/141.3
Midterm Examination
February 17, 2017
Time: 90 minutes
*********************** Solution &amp; Marking Guide ***********************
NSID:
Part I — Multiple Choice
Choose the best answer for each question. Choose only one answer per question.
Section 1: Identification
(0) 1. What section of the course are you in?
A. M/W/F, 11:30am (Jeff Long)
B. Tu/Th, 11:30am (Ralph Deters)
C. Tu/Th, 10:00am (Michael Long)
Section 2: Multiple Choice Questions
(1) 2. Which one of the following statements about algorithms is true?
A. An algorithm must have exactly 6 actions, no more and no less.
B. An algorithm must contain actions, repetition, conditionals, and spicy soup.
C. An algorithm is a list of actions that describe how to perform a task or solve a
problem.
D. An algorithm is always written in a language called pseudocode.
E. An algorithm is a task that only computers can perform.
(1) 3. Which one of the following statements about algorithms is FALSE?
A. Algorithms written in more-or-less regular English are called pseudocode.
B. Algorithms written in a programming language are called computer programs.
C. Algorithms written in pseudocode can be understood and carried out by a computer.
D. Algorithms written in pseudocode are intended as communication between human beings.
E. Algorithms written as a computer program obey strict syntax so that a computer
can carry them out.
CMPT 113.3/141.3 Midterm
Page 1 of 17
February 17, 2017
NSID:
(1) 4. Which one of the following statements about abstraction and refinement is true?
A. Abstraction is good for computers and bad for people.
B. Refinement is the process of fixing errors in an abstract algorithm.
C. Refinement is something a computer can easily do.
D. Abstraction and refinement are essentially the same thing.
E. Abstraction allows people to think about actions without worrying about how
they are performed.
(1) 5. Which of the following Python expressions is an atomic literal expression? If none are
atomic literal expressions, choose &quot;None of the above.&quot;
A. 123
B. 3 + 2 + 1
C. &quot;atomic&quot;
D. atomic
E. None of the above.
(1) 6. Atomic data is:
A. Always a number.
B. A collection of data values.
C. Very small.
D. A single data value.
E. Used in nuclear applications.
(1) 7. Which of the following Python expressions is a compound data value? If none are compound, choose &quot;None of the above.&quot;
A. 3 + 2 + 1
B. &quot;atomic&quot;
C. 123
D. atomic == 0
E. None of the above.
(1) 8. Which of the following is NOT a data type?
A. List
B. String
C. Argument
D. All of the above are data types
E. None of the above are data types
CMPT 113.3/141.3 Midterm
Page 2 of 17
February 17, 2017
NSID:
(1) 9. Which one of the following statements is true?
A. The expression 1 is a floating point literal.
B. The expression 1.0 is a floating point literal.
C. The expression 1.0 is an integer literal.
D. The expression &quot;1&quot; is an integer literal.
E. The expression one is a string literal.
(1) 10. Which of the following is NOT a valid Python expression?
A. 1.0 + 3
B. &quot;mew&quot; + 2
C. 1.7 + 5
D. True or False
E. 0 % 3
(1) 11. Assume the boolean variables fire and water describe the type of a Pokemon. Which of
the following Python expressions means &quot;the pokemon is either fire type or water type, but
not both&quot;?
A. (not fire and not water) and (fire or water)
B. fire or water
C. not (fire and water) and (fire or water)
D. not fire or not water
E. None of the above
(1) 12. Which one of the following is NOT a legal variable name (not a valid identifier)?
A. jane3
B. 3jane
C. threeJane
D. three_jane
E. _3_jane
CMPT 113.3/141.3 Midterm
Page 3 of 17
February 17, 2017
NSID:
Assume that the following variable declarations and initializations are given for questions 13 — 19.
f1
f2
f3
i1
i2
i3
=
=
=
=
=
=
1.5
3
0.0
8
3
0
(1) 13. What is the value of the expression i2 * f1 - 4 / i1?
A. 4
B. 4.0
C. 7
D. -4.0
E. 4.5
(1) 14. What is the value of the expression i2 * f1 - 4 // i1?
A. 4
B. 7
C. -4.0
D. 4.5
E. 4.0
(1) 15. What is the value of the expression i1 % i2 + i1?
B. 9
A. 10
C. 8
D. 7
E. 6
(1) 16. What is the value of the variable i2 after the following assignments statements in the order
given:
i3 = i1
i1 = i2
i2 = i3
A. 0
B. 8
C. 3
D. 1.5
E. None
(1) 17. What is the value of the expression (use the original values, ignoring the effects of the
previous quesiton):
(0 ! = i1) or (i1 &lt; 10)
A. True
B. False
(1) 18. What is the value of the expression:
(0 ! = i1) and (i1 &lt; 10)
A. True
B. False
(1) 19. What is the value of the expression:
((i1 &lt;= i1) &amp;&amp; (i2 &lt; f2) &amp;&amp; (i1 == 7)) || ((i1+i2) &gt; i2)
A. True
B. False
CMPT 113.3/141.3 Midterm
Page 4 of 17
February 17, 2017
NSID:
(1) 20. What does the term ’immutable’ mean? What is an example of an ’immutable’ data type?
A. Immutable means changeable. Lists are immutable.
B. Immutable means changeable. Booleans are immutable.
C. Immutable means unchangeable. Lists are immutable.
D. Immutable means unchangeable. Strings are immutable.
E. Immutable means hating mutants (like the X-Men). Dictionaries are immutable.
(1) 21. All strings have a method named upper, that takes no arguments, and returns a new string
with all lower case characters converted to upper case. Which of the following is a correct
call to the method upper?
A. upper(&quot;I’m not shouting&quot;)
B. &quot;I’M NOT SHOUTING&quot;
C. upper.&quot;I’m not shouting&quot;()
D. str(upper(&quot;I’m not shouting&quot;))
E. &quot;I’m not shouting&quot;.upper()
(1) 22. The module nemo has a function named go, that takes a string as an argument, and then
displays a clever story about the string (it uses Google, but that doesn’t matter). Which of
the following is a correct call to the function go, assuming that the import statement looks
like this:
import nemo as nemo
A. go.nemo(&quot;Sydney&quot;)
B. go(&quot;Sydney&quot;)
C. nemo.go(&quot;Sydney&quot;)
D. &quot;Sydney&quot;.go()
E. nemo(go(&quot;Sydney&quot;))
(1) 23. After the following assignment statement, what value does the variable x refer to?
x = print(42)
A. 42
B. ’42’
C. None
D. ’x’
E. ’print(42)’
CMPT 113.3/141.3 Midterm
Page 5 of 17
February 17, 2017
NSID:
Assume that the following variable declarations and initializations are given for questions 24 — 28.
example = &quot;bhmoeitlstpnlage&quot;
(1) 24. Which one of the following expressions has the string ’be’ as its value?
A. example[0]+example[len(example)]
B. example[0]+example[len(example)-1]
C. example[0:len(example)-1]
D. example[0]:example[len(example)]
E. [example[0],example[len(example)-1]]
(1) 25. Which one of the following strings is the value of the expression example[5:10]?
A. ’itls’
B. ’itlst’
C. ’itlstp’
D. ’eitlst’
E. ’eitls’
(1) 26. Which one of the following strings is the value of the expression example[0:len(example):3]?
A. ’bmetsplg’
B. ’besl’
C. ’bottle’
D. ’helpa’
E. ’bhmoeitlstpnlage’
(1) 27. Which one of the following expressions has the string ’msg’ as its value?
A. example[3:len(example):6]
B. example[2:len(example):5]
C. example[3:len(example):5]
D. example[-2:0:-6]
E. example[2:len(example):6]
(1) 28. How would you slice the string example to produce the value: ’egalnptsltieomhb’
A. example[len(example):0]
B. example[0:len(example):-1]
C. example[len(example):0:-1]
D. example[0:len(example)]
E. example[0:len(example):0]
CMPT 113.3/141.3 Midterm
Page 6 of 17
February 17, 2017
NSID:
Answer each question in the space provided on this question paper.
Section 1: Creating Functions
(2) 29. Write a Python function called doubleString that accepts a string value s as a parameter
and returns a string that is simply s repeated twice (e.g. if your function is called with an
argument of &quot;Pika&quot;, it should return the value &quot;PikaPika&quot;).
Solution:
def doubleString(s):
return s*2
Marking guide:
• (1) for function header with parameter
• (1) for correct return value.
Section 2: Conditional Branching
(4) 30. Write Python code that obtains an integer from the console using the input() function
and displays on the console a message using the print() function indicating whether the
integer is evenly divisible by 17 or not.
Solution:
x = int(input(’A prompt may be used:’))
if x % 17 == 0:
print(’Number is divisible by 17.’)
else:
print(’Number is not divisible by 17.’)
Marking guide:
CMPT 113.3/141.3 Midterm
Page 7 of 17
February 17, 2017
NSID:
• (1) correct use of input() with typecast
• (1) correct if-elseif structure/syntax
• (1) correct condition with if-statement.
• (1) appropriate messages printed.
CMPT 113.3/141.3 Midterm
Page 8 of 17
February 17, 2017
NSID:
(4) 31. Write Python code that checks if an existing variable letter is a lowercase vowel. If it is
a, e, i, o, or u, print out Yes, it is a lowercase vowel. If the letter is y, print out
The letter might be a lowercase vowel. If the letter is anything else, print out
No, the letter is not a lowercase vowel.
Solution:
if letter == ’a’ or letter == ’e’ or letter == ’i’ or letter == ’o’ or letter == ’u’:
print(&quot;Yes, it is a vowel&quot;)
elif letter == ’y’:
print(&quot;The letter might be a vowel&quot;)
else:
print(&quot;No, the letter is not a vowel&quot;)
Marking guide:
• (1) correct use of multiple ’or’ operators in the condition.
• (1) correct approach of using elif to test for ’y’, half mark if they used nested if.
• (1) correct approach of handling all other letters in the else condition
• (1) correct syntax of conditional structure.
Section 3: Loops
(3) 32. Write Python code that reads a word of text from the console using the input() function
and continues asking for a valid word until the user enters a word that contains only letters.
Hint: You can test whether a string contains only letters by using the string’s isalpha()
method which returns True if the string contains only letters, and False otherwise.
Solution:
word = input(’Enter a word: ’)
while(not word.isalpha()):
print(’Your word must contain only letters.’)
word = input(’Enter a word: ’)
#optional
Marking guide:
• (1) correct use of input()
• (1) correct while loop structure/syntax
• (1) correct loop condition
Note: the printing of an error message is optional
CMPT 113.3/141.3 Midterm
Page 9 of 17
February 17, 2017
NSID:
(4) 33. Suppose you have a list of strings called teams storing the names of teams in a sports
tournament. The tournament is a round-robin tournament in which each team has to play
each other team. Write a loop which prints out a complete list of all of the team matchups
for the games that must be played; that is, each line of output must be Team 1 vs. Team
2 where ’Team 1’ and ’Team 2’ are strings from teams.
Hint 1: A team does not play itself.
Hint 2: Each match-up should only be printed once. So if you’ve already printed Team 1
vs. Team 2, you should not also print Team 2 vs. Team 1.
Solution:
for x in range(len(teams)):
for y in range(x+1, len(teams)):
print(teams[x], ’vs.’, teams[y])
Marking guide:
• (1) correct nested loop structure and syntax
• (1) correct range for outer loop
• (1) correct range for inner loop
• (1) correct print statement
Note: Students may attempt to do this without using range and indices, e.g. for x in
teams:. This is hard because there is no way for the inner loop to avoid iterating over
everything. They are likely to print each pair twice, as well as equal pairs. Assuming
everything else is OK, deduct 1 mark if they print out pairs twice but avoid having teams
play themselves. Deduct 2 if they also do not check for the latter.
Section 4: Lists
(4) 34. Suppose you have two variables list1 and list2 that refer to lists of strings, and that each
list is the same length. Write code that generates a new list that contains all of the matching
items from list1 and list2. An item is a match if the same item occupies exactly the
same index in both list1 and list2. For example, if list1 is [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]
and list2 is [&quot;a&quot;,&quot;c&quot;,&quot;b&quot;,&quot;d&quot;], then the new list you create should be [&quot;a&quot;,&quot;d&quot;],
because &quot;a&quot; and &quot;d&quot; were in the same position in both lists.
Solution: Typical solution (could use for loop or while loop):
CMPT 113.3/141.3 Midterm
Page 10 of 17
February 17, 2017
NSID:
new_list = []
for i in range(len(list1)):
if list1[i] == list2[i]:
new_list.append(list1[i])
Marking guide:
• (1) Initialize empty list
• (1) for correct for or while loop
• (1) for correct list indexing
• (1) for appending correct item
CMPT 113.3/141.3 Midterm
Page 11 of 17
February 17, 2017
NSID:
(3) 35. Suppose that you have a variable list_of_lists that refers to a list in which each data
item is, itself, a list of strings. Write code which sets the variable longest_string to refer
to the longest string in any of the lists of strings. e.g. if list_of_lists is
[ [’a’, ’bb’, ’cc’], [’e’, ’fff’, ’gg’ ] ]
then at the conclusion of your program, longest_string should refer to ’fff’. (But
remember that list_of_lists could refer to any list of lists!)
If there are multiple longest strings with the same length, then it does not matter which of
Solution:
longest_string = ’’
total_strings = 0
for x in list_of_lists:
for y in x:
if len(y) &gt; len(longest_string):
longest_string = y
You might also see a lot of this:
longest_string = ’’
total_strings = 0
for x in range(len(list_of_lists)):
for y in range(len(list_of_lists[x])):
if len(list_of_lists[x][y]) &gt; len(longest_string):
longest_string = list_of_lists[x][y]
Marking guide:
• (1) Appropriate initialization of longest_string and total_strings
• (2) for correctly determining longest_string
(2) 36. Suppose that a variable grades refers to a list where each data item is a list containing two
items: a student’s name and their course percentage grade, e.g.
[ [’Phoenix Wright’, 75], [’Mia Fey’, 99], ...
]
Write a list comprehension that creates a list of lists that contains only the sublists (student
name and grade) of those students who got more than 70% in the class.
Solution:
[x in grades if x[1] &gt; 70]
CMPT 113.3/141.3 Midterm
Page 12 of 17
February 17, 2017
NSID:
Marking guide:
• (1) syntax of list comprehension is correct
• (1) condition is correct
CMPT 113.3/141.3 Midterm
Page 13 of 17
February 17, 2017
NSID:
(2) 37. Suppose that a variable prices refers to a list of floating-point numbers that are the prices
of the items in a customers shopping cart on an online store website. Write a list comprehension that creates a new list of prices that have had a 15% sales tax added to each
original price.
Solution:
[x * 1.15 for x in prices]
Marking guide:
• (1) syntax of list comprehension is correct
• (1) expression x * 1.15 is correct
Section 5: Dictionaries
(4) 38. Phoenix Wright &amp; Co. Law Office keeps track of each legal case it takes on, and in an effort
to gain more clients, they want to calculate the total number cases they have won. Suppose
that the Python variable cases refers to a dictionary in which keys are case names (strings)
and values are the result of that case (boolean) which is True if Wright &amp; Co. won the case,
and False if they lost the case.
An example entry from cases might be: &quot;DX4&quot; :
True
Write Python code that prints out the total number of cases that have been won. Hint: the
function len(sequence) may be useful for some styles of solutions.
Solution:
# Counting way
num_cases_won = 0
for a_case in cases:
if cases[a_case] == True:
num_cases_won = num_cases_won + 1
print(num_cases_won)
# Making a new list, then using len() way
won_cases = []
for a_case in cases:
if cases[a_case] == True:
won_cases.append(a_case)
print (len(won_cases))
CMPT 113.3/141.3 Midterm
Page 14 of 17
February 17, 2017
NSID:
# List comprehension solution
cases_won = [ c for c in cases if cases[c] ]
print(len(cases_won))
Marking guide:
• (1) correct iteration over dictionary keys
• (1) correct indexing of dictionary
• (1) correct condition
• (1) correct printing of the values
CMPT 113.3/141.3 Midterm
Page 15 of 17
February 17, 2017
NSID:
(4) 39. The aspiring Pokemon trainer, Ash Ketchum, is compiling a list of Pokemon gym leaders
that he wants to store in a database. He has compiled the following table of data so far:
Name
Brock
Misty
Lieutenant Surge
Number of Pokemon
3
4
6
Favorite Type
Rock
Water
Lightning
City
Pewter
Cerulean
Vermillion
Write a Python dictionary literal that contains the above data such that the dictionary is
keyed on gym leader name, and each such key is associated with a record (i.e. another dictionary) with keys ’number’, ’fav_type’, ’city’ each associated with their respective
values from the table above.
Solution:
{
’Brock’ : { ’number’:3, ’fav_type’:’Rock’, ’city’:&quot;Pewter&quot; },
‘Misty’ : { ’number’:4, ’fav_type’:’Water’, ’city’:’Cerulean’ },
’Lieutenant Surge’ : { ’number’:6, ’fav_type’:’Lightning’, ’city’:’Vermillion’ }
}
Marking guide:
• (1) Braces around entire dictionary
• (1) Correct use of ’:’ to separate keys and values at both levels
• (1) Correct placement of commas between key-value pairs at both levels
• (1) Correct nesting of dictionaries.
CMPT 113.3/141.3 Midterm
Page 16 of 17
February 17, 2017
NSID:
CMPT 113.3/141.3 Midterm
Page 17 of 17
February 17, 2017
```