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:
PYTHON
left ='L'right ='R'temp = leftleft = rightright = temp
Compare it to:
PYTHON
left, right = right, left
Do they always do the same thing? Which do you find easier to
read?
Both examples exchange the values of left and
right:
PYTHON
print(left, right)
OUTPUT
R L
In the first case we used a temporary variable temp to
keep the value of left before we overwrite it with the
value of right. In the second case, right and
left are packed into a tuple and then unpacked into
left and right.
Turn a String into a List
Use a for-loop to convert the string “hello” into a list of
letters:
Knowing that two strings can be concatenated using the +
operator, write a loop that takes a string and produces a new string
with the characters in reverse order, so 'Newton' becomes
'notweN'.
Fix range_overlap. Re-run
test_range_overlap after each change you make.
PYTHON
def range_overlap(ranges):'''Return common overlap among a set of [left, right] ranges.'''ifnot ranges:# ranges is None or an empty listreturnNone max_left, min_right = ranges[0]for (left, right) in ranges[1:]: max_left =max(max_left, left) min_right =min(min_right, right)if max_left >= min_right: # no overlapreturnNonereturn (max_left, min_right)