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 = tempCompare it to:
left, right = right, leftDo they always do the same thing? Which do you find easier to read?
Solution
Both examples exchange the values of
leftandright:print(left, right)R LIn the first case we used a temporary variable
tempto keep the value ofleftbefore we overwrite it with the value ofright. In the second case,rightandleftare packed into a tuple and then unpacked intoleftandright.
Turn a String into a List
Use a for-loop to convert the string “hello” into a list of letters:
["h", "e", "l", "l", "o"]Hint: You can create an empty list like this:
my_list = []Solution
my_list = [] for char in "hello": my_list.append(char) print(my_list)
Reverse a String
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'.Solution
newstring = '' oldstring = 'Newton' for char in oldstring: newstring = char + newstring print(newstring)
Fixing and Testing
From: “Defensive Programming”
Fix
range_overlap. Re-runtest_range_overlapafter each change you make.Solution
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[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 overlap return None return (max_left, min_right)