Final Practice Set
Final Practice Set
The following questions are taken from www.coursera.org s Learn to Program: The Fundamentals. This
is simple copy paste stuff, so should be dealt with intelligence and relevance in mind.
Question 1
Select the expression(s) that evaluate to True .
'bit' in 'habit'
len('deed') == 4
len('deed') == 2
'sit' in 'tis'
Question 2
What does the expression len('') evaluate to?
Question 3
After the following assignment statement has been executed, which expression(s) evaluate to the
letter "g" ?
dance_style = "Vogue"
dance_style[-4]
dance_style[3]
dance_style[2]
dance_style[-3]
Question 4
Consider the following code:
title = 'King'
Using title and indexing (not slicing), write an expression that gives 'n' .
Answer for Question 4
Question 5
Considering the following code:
s = 'pineapple'
s[4:len(s)]
s[4:9]
s[5:]
s[-5:-1]
Question 6
Consider the following code:
prefix = 'mad'
What does the expression prefix[:1] + prefix[1:3] + prefix[-2] + prefix[0] evaluate to?
Answer for Question 6
Question 7
Select the expression(s) that evaluate to True .
'apple'.upper().islower()
'apple'.upper() == 'APPLE'
'abc123'.isalnum()
'12.34'.isalnum()
Question 8
Select the expression(s) that evaluate to True when variable s refers to a str that is entirely
alphabetic or entirely numeric, and that evaluate to False if they are not entirely alphabetic and not
entirely numeric.
s.isalpha() and s.isnumeric()
s.islower() or s.isupper()
s.isalpha() or s.isnumeric()
Question 9
Variables s1 and s2 refer to str s. The expression s1.find(s2) returns the index of the first
occurrence of s2 in s1 .
Write an expression that gives the index of the second occurrence of s2 in s1 . If s2 does
not occur twice in s1 , the expression should evaluate to -1 . Unlike str.count , you should
allow overlapping occurrences of s2 .
Your answer must be a single expression that does not use the square bracket notation,
and you can only call method str.find and use the arithmetic operators (+, -, etc.).
Hint: method str.find has an optional second parameter. You can find out more by
calling help(str.find) .
Question 10
Consider the following code:
digits = '0123456789'
result = 100
print(result)
55
Question 11
Consider the following code:
digits = '0123456789'
result = 0
result = digit
print(result)
45
Question 12
Consider the following code:
digits = '0123456789'
result = ''
print(result)
45
0123456789
90
Question 13
Select the code fragment(s) that print Happy 30th! .
new_message = ''
for char in message:
if char.isdigit():
print(new_message)
new_message = ''
if char.isdigit():
else:
print(new_message)
new_message = ''
print(new_message)
if not char.isdigit():
else:
print(new_message)
Question 14
Part of the body of the following function is missing. Select the missing code fragment.
def common_chars(s1, s2):
Return a new string containing all characters from s1 that appear at least
once in s2. The characters in the result will appear in the same order as
'a'
'a'
'abb'
'araaara'
'''
res = ''
# BODY MISSING
return res
for ch in s1:
if ch in s2:
res = res + ch
for ch in s1:
if ch in s2:
res = ch + res
for ch in s1:
for ch in s2:
res = res + ch
if ch in s2:
for ch in s1:
res = res + ch
Question 1
Select the expression(s) that evaluate to True .
len('mom') in [1, 2, 3]
'3' in [1, 2, 3]
Question 2
Consider the code:
def secret(s):
i = 0
result = ''
while s[i].isdigit():
i = i + 1
return result
secret('123')
secret('abc')
secret('abc123')
secret('123abc')
Question 3
Consider the code:
def example(L):
''' (list) -> list
'''
i = 0
result = []
result.append(L[i])
i = i + 3
return result
Return a list containing the items from L starting from index 0, omitting every third item.
Question 4
def compress_list(L):
and so on.
['ab', 'cd']
'''
compressed_list = []
i = 0
return compressed_list
i = i * 2
i = i + i
i = i + 1
i = i + 2
Question 5
What is the sum of the odd numbers from 1523 through 10503, inclusive? Hint: write a while loop
to accumulate the sum and print it. Then copy and paste that sum. For maximum learning, do it with
a for loop as well, using range .
Question 6
Consider the code:
def while_version(L):
i = 0
total = 0
i = i + 1
return total
The while loop stops as soon as an even number is found, and the sum of all the previous numbers
is returned. The four functions below use a for loop to try to accomplish the same task, although
they keep iterating through all of the numbers in L regardless of whether the numbers are even or
odd. Only one of them returns the same value as function while_version . Which one is it?
def for_version(L):
found_even = False
total = 0
for num in L:
if num % 2 != 0:
found_even = True
return total
def for_version(L):
found_even = False
total = 0
for num in L:
else:
found_even = True
return total
def for_version(L):
found_even = False
total = 0
for num in L:
if num % 2 != 0:
found_even = True
return total
def for_version(L):
found_even = False
total = 0
for num in L:
if num % 2 != 0:
found_even = True
return total
Question 7
Consider the code:
>>> print(numbers)
[3, 4, 1]
Which of the following code fragments(s) could be the missing code in the program above?
reverse(numbers)
numbers.reverse()
numbers = numbers.reverse()
numbers = reverse(numbers)
Question 8
Consider the code:
veggies.insert(veggies.index('broccoli'), 'celery')
print(veggies)
What is displayed by the code above?
Question 9
Your younger sibling has just discovered music from the 1970's. They have put together a playlist of
the same 5 songs repeated again and again. Here are the songs:
You want to make sure that Lola only gets played 3 times, so you want to complete this function
that edits the playlist:
def cap_song_repetition(playlist, song):
'''
playlist.pop(playlist.index(song))
playlist.remove(song)
playlist.remove(playlist.index(song))
playlist.remove(song)
Question 10
Consider the code:
>>> a = [1, 2, 3]
>>> b = a
>>> print(a, b)
Which of the following code fragments(s) could be the missing code in the program above?
a[1] = 'A'
b[1] = 'AB'
a[1] = a[1][0]
a = [1, 'A', 3]
b = [1, 'A', 3]
b[-2] = 'A'
Question 11
Consider the code:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> print(a, b)
Which of the following code fragments(s) could be the missing code in the program above?
a[1] = 'A'
b[1] = 'AB'
a[1] = a[1][0]
b[-2] = 'A'
a = [1, 'A', 3]
b = [1, 'A', 3]
Question 12
Consider the code:
def increment_items(L, increment):
i = 0
i = i + 1
values = [1, 2, 3]
print(increment_items(values, 2))
print(values)
[3, 4, 5]
None
[3, 4, 5]
[1, 2, 3]
None
[1, 2, 3]
None
[3, 4, 5]
Question 13
Select the code fragment(s) that print [3, 6, 9] .
values = []
values.append(num)
print(values)
values = []
values.append(num)
print(values)
values = []
values.append(num * 3)
print(values)
values = []
values.append(num * 3)
print(values)
Question 14
Select the function calls to range that, when used to fill in the blank, cause the code to produce the
results below.
print(num)
11
19
range(3, 20, 8)
range(3, 19, 8)
range(3, 8, 20)
range(3, 23, 8)
Question 1
Consider the code:
def merge(L):
merged = []
return merged
print(merge([1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 7]
def mystery(s):
'''
matches = 0
if s[i] == s[len(s) - 1 - i]: # <--- How many times is this line reached?
matches = matches + 1
Trace the function call mystery('civil') using the Python Visualizer. How many times is the line
Question 3
Consider the code:
def mystery(s):
'''
matches = 0
Return True if and only if the number of duplicate characters in s is equal to len(s) // 2 .
Return True if and only if there are exactly len(s) // 2 characters in s that are the same
character.
Question 4
In one of the Week 6 lecture videos, we wrote the function shift_left . Consider this function, which
def shift_right(L):
'''
last_item = L[-1]
Hint: the correct answer works from the end to the beginning of L .
for i in range(len(L)):
L[i + 1] = L[i]
L[i] = L[i + 1]
L[len(L) - i] = L[len(L) - i - 1]
L[i] = L[i + 1]
Question 5
Consider the code (these type contracts get a little tough to write!):
''' (list of str, list of int) -> list of [str, int] list
Return a new list in which each item is a 2-item list with the string from the
corresponding position of list1 and the int from the corresponding position of li
st2.
'''
pairs = []
return pairs
Select the code fragment(s) that make the function above match its docstring description.
for i in range(len(list1)):
inner_list = []
inner_list.append(list1[i])
inner_list.append(list2[i])
pairs.append(inner_list)
for i in range(len(list1)):
pairs.append([list1[i], list2[i]])
for i in range(len(list1)):
inner_list = []
inner_list.append(list1[i])
inner_list.append(list2[i])
pairs.append(inner_list)
inner_list = []
for i in range(len(list1)):
inner_list.append(list1[i])
inner_list.append(list2[i])
pairs.append(inner_list)
Question 6
Consider the code:
Using values and indexing with non-negative indices, write an expression that produces 5 . Do
Question 7
Consider the code:
Using treats and indexing with only negative indices, write an expression that produces 'pie' .
print(i, j)
Trace the code above in the Python Visualizer. How many times is print(i, j) executed?
15
24
Question 9
Consider the code:
True
'''
Select the code fragment(s) that make the function above match its docstring description.
for i in range(len(lst)):
for j in range(len(lst[i])):
for i in range(len(lst)):
for j in range(len(lst[i])):
if lst[i][j] == value:
found = True
if value == item:
value = True
if value in sublist:
found = True
Question 10
A file has a section at the top that has a preamble describing the contents of the file, then a
blank line, then a list of high temperatures for each day in January all on one line, then a list
of high temperatures for each day in February all on one line, then lists for March, April, and
so on through December, each on one line. There are thousands of lines of information
after that temperature data that you aren't currently interested in.
You want to write a program that prints the average of the high temperatures in January.
Which of the four file-reading approaches should you use?
Question 11
Consider the code:
print(line)
The program above prints the lines of the file but adds an extra blank line after each line. Select the
code fragment(s) that when used as replacement(s) for print(line) will print the lines without extra
blank lines.
Note: use help to find out information about any functions or methods that you are not familiar with.
print(line, end='')
print(line.rstrip('\n'))
print(line - '\n')
print(line.strip())
Question 12
Consider the code:
Return the list of lines from file that begin with letter. The lines should have
the
newline removed.
Precondition: len(letter) == 1
'''
matches = []
return matches
Select the code fragment(s) that make the function above match its docstring description.
if letter == line[0]:
matches.append(line.rstrip('\n'))
if letter in line:
matches.append(line.rstrip('\n'))
for line in file:
matches.append(line.startswith(letter).rstrip('\n'))
if line.startswith(letter):
matches.append(line.rstrip('\n'))
Question 13
Consider the code:
'''
Select the code fragment(s) that make the function above match its docstring description.
for s in sentences:
file.write(s)
file.write('\n')
for s in sentences:
file.write(s)
file.write('\n')
for s in sentences:
file.write(s)
file.write(sentences)
for s in sentences:
file.write(s + '\n')