Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Lesson 09 – Lists

Exercises.

1. Write a function that takes a list of numbers and returns the cumulative sum; that
is, a new list where the ith element is the sum of the first i + 1 elements from the
original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].

2. Write a function called chop that takes a list and modifies it, removing the first and
last elements, and returns None. Then write a function called middle that takes a list and
returns a new list that contains all but the first and last elements.

3. Write a function called is_sorted that takes a list as a parameter and returns True
if the list is sorted in ascending order and False otherwise. You can assume (as a
precondition) that the elements of the list can be compared with the relational
operators <, >, etc. For example, is_sorted([1,2,2]) should return True and
is_sorted(['b','a']) should return False.

4. Two words are anagrams if you can rearrange the letters from one to spell the other.
Write a function called is_anagram that takes two strings and returns True if they are
anagrams.

5. Lists can be used to represent mathematical vectors. Write a function


add_vectors(u, v) that takes two lists of numbers of the same length, and returns a
new list containing the sums of thecorresponding elements of each:

add_vectors([1, 1], [1, 1]) -> [2, 2]


add_vectors([1, 2], [1, 4]) -> [2, 6]
add_vectors([1, 2, 1], [1, 4, 3]) -> [2, 6, 4])

6. Write a function scalar_mult(s, v) that takes a number, s, and a list, v and returns
the scalar multiple of v by s.

scalar_mult(5, [1, 2]) -> [5, 10]


scalar_mult(3, [1, 0, -1]) -> [3, 0, -3]
scalar_mult(7, [3, 0, 5, 11, 2]) -> [21, 0, 35, 77, 14]

7. Write a function dot_product(u, v) that takes two lists of numbers of the same
length, and returns the sum of the products of thecorresponding elements of each (the
dot_product).

dot_product([1, 1], [1, 1]) -> 2


dot_product([1, 2], [1, 4]) -> 9
dot_product([1, 2, 1], [1, 4, 3]) -> 12

8. Write a function cross_product(u, v) that takes two lists of numbers of length 3


and returns their cross product.

You might also like