A collection of exercises that have been either removed from or not (yet) added to the main lesson.
Swapping the contents of variables (5 min)
Explain what the overall effect of this code is:
left = 'L' right = 'R' temp = left left = right right = temp
Compare it to:
left, right = right, left
Do they always do the same thing? Which do you find easier to read?
Both examples exchange the values of
In the first case we used a temporary variable
tempto keep the value of
leftbefore we overwrite it with the value of
right. In the second case,
leftare packed into a tuple and then unpacked into
Fixing and Testing
From: “Defensive Programming”
test_range_overlapafter each change you make.
def range_overlap(ranges): '''Return common overlap among a set of [left, right] ranges.''' if not ranges: # ranges is None or an empty list return None max_left, min_right = ranges for (left, right) in ranges[1:]: max_left = max(max_left, left) min_right = min(min_right, right) if max_left >= min_right: # no overlap return None return (max_left, min_right)