Lecture 15 Finger Exercise

The questions below are due on Friday May 08, 2026; 11:59:00 PM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.

Question 1. In class, we saw the following function, which runs adjacent elements of a sequence through a compare() function provided as a parameter.
def compare_adjacents(seq, compare):
    result = []
    for i in range(1, len(seq)):
        result.append(compare(seq[i - 1], seq[i]))
    return result

Ben Bitdiddle claims that there is no equivalent lambda expression for square_or_sum() below, and hence the following call to compare_adjacents() must be made with variable name that points to a function object.

def square_or_sum(a, b):
    if a < b:
        return b**2
    elif a > b:
        return a**2
    else:
        return a + b

compare_adjacents(seq, square_or_sum)

Show otherwise by writing in the box below an equivalent call to compare_adjacents() that passes in a lambda expression for the second argument. Assume that seq is already defined globally.

Hint: We had seen a similar pattern in class using a conditional expression, but that handled only two branching possibilities. To handle three possibilities, think about if conditional expressions can be nested.

Question 2. Charlene D. Vice has two lists of numbers of the same length, seq_a and seq_b, and she would like to produce a new list by taking the element-wise sum of their elements. For example, if seq_a = [3, 7, 5], and seq_b = [4, 1, -14], then the result should be [7, 8, -14].

Charlene proposes the following list comprehension to accomplish this task.

[x + y for x in seq_a for y in seq_b]

Unfortunately, it doesn't give the result she intended. Try out Charlene's code in your own Python REPL to see what it produces. Then, write in the box below a correct list comprehension for this task. Assume that seq_a and seq_b are already defined globally.