Exercises for Lesson 5
Exercise 0: Playing with chr
and ord
Show the output that would be generated by the following program fragment:
msg = ""
for ch in "banana":
mystery = chr(ord(ch) + 4)
print(mystery)
Exercise 1: Basic List operations
For this exercise, we’ll use the following statements:
numbers = [3, 1, 4, 1, 5]
words = ["apple", "banana", "cat", "dog", "elephant"]
Predict the result of evaluating each of the following list expressions.
a) numbers + words
b) 2 * numbers + words
c) numbers[-1]
d) words[1:4]
e) words[1] + words[2]
f) len(numbers)
g) for word in words:
print(word[:3])
Exercise 2: For-loop Patterns
Write a for
loop using the variables numbers
and words
to generate each output. Think about whether you need the element and/or its index for each loop.
numbers = [3, 1, 4, 1, 5]
words = ["apple", "banana", "cat", "dog", "elephant"]
a) ae
ba
ct
dg
et
b) 0 apple
1 banana
2 cat
3 dog
4 elephant
c) 3
1
4
1
5
Exercise 3: Going backwards
Exercise 3a: building a new result
Write a program to print a sequence of words in reverse order. You cannot use slicing or the existing reverse
list method. (Hint: you should use split
to turn the provided string into a list
, and use the accumulator pattern to build the resulting list in reversed order.)
Here is an example interaction:
Please enter a sequence of words, separated by spaces: apple banana cat dog elephant fish
The sequence reversed:
fish elephant dog cat banana apple
Just for fun, see if you can build the resulting reversed list using a single slicing operation.
Exercise 3b: reversing in place
Now, instead of building up a new reversed result, reverse the provided list in-place, i.e. by modifying the original list, without using any additional variables. (Hint: remember that Python allows for simultaneous assignment.)
Here is an example interaction:
>>> mylist = ["apple", "banana", "cat"]
>>> mylist
['apple', 'banana', 'cat']
>>> YOUR CODE HERE
>>> mylist
['cat', 'banana', 'apple']