Review the class notes and examples from this week covering lists. In particular, recall there are built-in functions that apply to lists:
len(L)
Returns the number of items in list Lmax(L)
Returns the maximum value in list Lmin(L)
Returns the minimum value in list Lsum(L)
Returns the sum of the values in list Lsorted(L)
Returns a copy of list L where the items are in order from
smallest to largest (this does not mutate L.)Furthermore, the Python documentation for lists includes links to operations and methods that apply to common sequence types and mutable sequence types including lists.
Answer these two questions on Gradescope.
Question 1: Write a Python expression that sorts a list data
in place.
For example, if data
were the list [45, 6.2, -3.5, 10] then after execution of your expression
the list data
would contain [-3.5, 6.2, 10, 45].
Question 2: Write a sequence of Python statements that given a non-empty list would
return the middle value in the list. For an odd number of data elements, this is the value
in position len(list) // 2. For an even number of data elements, return the average of
the two middle items.
For example, if data
were the list [35, 14, 10, 81, 40] then middle(data)
would
evaluate to 10
. If data
were the list [35, 14, 10, 81] then middle(data)
would
evaluate to 12
, the average of 14
and 10
.
Your statements would complete the following code
if pasted in:
def middle(sequence):
"""
Returns middle value in non-empty sequence
Args:
sequence: a sequence of values of any type, sorted or unsorted
Returns:
the middle element if sequence has odd length, or the average
of the two middle elements if sequence has even length
"""
Review the lab assignment carefully before lab so you are ready to go. You will work during lab with a partner using a technique called Pair Programming.