The following exercises provide additional practice problems (not to turn in) for our material this week. Try to solve each problem on paper / whiteboard first before using Thonny to confirm your answers. You are encouraged to work on these practice exercises with classmates throughout the week.
[PP Problem 8.4] The value of the variable ids
is the list [4353, 2314,
2956, 3382, 9362, 3900]
. Using list
methods,
do the following:
a. Remove 3382 from the list.
b. Get the index of 9362.
c. Insert 4499 in the list after 9362.
d. Extend the list by adding [5566, 1830] to it.
e. Reverse the list.
f. Sort the list.
Since strings and lists are both sequences, many Python expressions can be
applied to both string values and list values. For each of the expressions
below, determine whether the expression is valid both when value
is a string or a list; or only if value
is a string; or only if value
is a list.
value + value
[value]
len(value)
value[:4]
"abc" + value
Write docstrings for the following functions describing what each of them do:
Mystery Function 1
def mystery1(num1, num2):
result = []
for i in range(num1):
result.append(num2)
return result
Mystery Function 2
def mystery2(num1, num2):
return [num2]*num1
Mystery Function 3
def mystery3(a_list):
for i in range(len(a_list) // 2):
other_index = len(a_list)-i-1
temp = a_list[i]
a_list[i] = a_list[other_index]
a_list[other_index] = temp
[PP Problem 8.7] Write a function named same_first_last
that takes a list
as a parameter and returns True
if and only if the first and last element
of the list are equal. You can assume that the list has at least one
element.
[PP Section 8.8] You are experimenting with the following code to provide a
list of colors in sorted order, but you are getting an error when your for
loop executes. What is the problem and how would you fix it?
colors = 'red orange yellow green blue purple'.split()
sorted_colors = colors.sort()
for color in sorted_colors:
print(color)
A professor typically teaches two courses a semester. Suppose at
the beginning of the semester they want to find out how many
students are enrolled in both their courses. Assume they have
two files containing the respective class rosters. Write a function
named common_students
that takes the two files as arguments and
returns the number of students whose names appear on both rosters. Recall
that you can use the in
operator to test if a value is present in
a list.