3.10. ExercisesΒΆ
-
What is the result of each of the following:
- ‘Python’[1]
- “Strings are sequences of characters.”[5]
- len(“wonderful”)
- ‘Mystery’[:4]
- ‘p’ in ‘Pineapple’
- ‘apple’ in ‘Pineapple’
- ‘pear’ not in ‘Pineapple’
- ‘apple’ > ‘pineapple’
- ‘pineapple’ < ‘Peach’
- ‘Python’[1] = ‘y’
- ‘Strings are sequences of characters.’[5] = ‘g’
- len(‘wonderful’) = 9
- ‘Mystery’[:4] = ‘Myst’
- ‘p’ in ‘Pineapple’ = True
- ‘apple’ in ‘Pineapple’ = True
- ‘pear’ not in ‘Pineapple’ = True
- ‘apple’ > ‘pineapple’ = False
- ‘pineapple’ < ‘Peach’ = False
-
Draw a reference diagram for
a
andb
before and after the third line of the following python code is executed:a = [1, 2, 3] b = a[:] b[0] = 5
Your diagram should show two variables referring to two different lists.a
refers to the original list with 1,2, and 3.b
refers to a list with 5,2, and 3 since the zero-eth element was replaced with 5.
-
Draw a reference diagram for
a
andb
before and after the third line of the following python code is executed:a = [1, 2, 3] b = 2*a c = 3*b c[0] = 5
- Question: Determine the complexity of the following task: Sum up all the negative numbers in a list.
-
Question: Determine the complexity of the following task: Count how many words in a list have length 5.
Answer:
To complete this task, we must
- visit each of the words in the list: \(n\) operations, each \(O(1)\).
- For each word, check if the word is longer than 5: \(n\) operations, each \(O(1)\).
- For each word larger than 5, add 1 to the count. Suppose there are \(m\) long words: \(m < n\) operations, each \(O(1)\).
Thus the total complexity is \(n*O(1) + n*O(1) + m*O(1) < n*(3*O(1)) = O(n*1) = O(n)\)
- Determine the complexity of the following task: Add up all of the entries of an \(n\times n\) matrix