Lecture 15 Finger Exercise
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.
Ben Bitdiddle claims that there is no equivalent lambda expression for Show otherwise by writing in the box below an equivalent call to 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.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
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)
compare_adjacents() that passes in a lambda expression for the second argument.
Assume that seq is already defined globally.
Charlene proposes the following list comprehension to accomplish this task. 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, 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].
[x + y for x in seq_a for y in seq_b]
seq_a and seq_b are already defined globally.