Below are exercises from chapter 11 of How to Think Like a Computer Scientist: Learning with Python 3. The text in italics comes from the textbook, and the code (except where it is obviously part of the textbook's prompt) is my solutions.

11.22.5 -- Add items in two lists
...

Lists can be used to represent mathematical vectors. In this exercise and several that follow you will write functions to perform standard operations on vectors. Create a script named vectors.py and write Python code to pass the tests in each case.

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 the corresponding elements of each:

test(add_vectors([1, 1], [1, 1]) == [2, 2]) 
test(add_vectors([1, 2], [1, 4]) == [2, 6]) 
test(add_vectors([1, 2, 1], [1, 4, 3]) == [2, 6, 4])

We can do this like so:

def add_vectors(u, v):
    """Add lists.

    Takes two lists of numbers of the same length,
    and returns a new list containing the sums of the corresponding
    elements of each.
    """
    new_list = []
    for i in range(len(u)):
        new_list.append(u[i] + v[i])
    return new_list

11.22.6 -- Multiply items in a list by a number
...

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.

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

Solution:

def scalar_mult(s, v):
    """Perform scalar multiplication.

    Take a number, s, and a list, v, and return the scalar multiple
    of v by s.
    """
    new_list = []
    for x in v:
        new_list.append(s * x)
    return new_list

11.22.7 -- Dot product
...

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 the corresponding elements of each (the dot product).

test(dot_product([1, 1], [1, 1]) ==  2)
test(dot_product([1, 2], [1, 4]) ==  9)
test(dot_product([1, 2, 1], [1, 4, 3]) == 12)

Solution:

def dot_product(u, v):
    """Return a dot multiple.

    Takes two lists of numbers of the same length, and returns the
    sum of the products of the corresponding elements of each (the
    dot product).
    """
    sum = 0
    for i in range(len(u)):
        sum += u[i] * v[i]
    return sum

11.22.8 -- Cross Product

Extra challenge for the mathematically inclined: Write a function cross_product(u, v) that takes two lists of numbers of length 3 and returns their cross product. You should write your own tests.

I may not be the most mathematically inclined person out there, but there's a pretty simple formula out there for cross-products, and it goes like this:

formula for calculating a cross-product

So all we have to do is just, in a very straightforward way, translate that formula into Python. Solution:

def cross_product(u, v):
    """Take two vectors and return their cross-product.

    Takes two lists of numbers, each of length three. Returns cross-product
    as a similar list."""

    a_x = u[0]               # Convert names just to make the formula being
    a_y = u[1]               # used incredibly clear. Think of the underscore _
    a_z = u[2]               # as making the next letter subscript.
    b_x = v[0]
    b_y = v[1]
    b_z = v[2]
    c_x = a_y * b_z - a_z * b_y   # Standard formula for cross-products.
    c_y = a_z * b_x - a_x * b_z
    c_z = a_x * b_y - a_y * b_x

    return [c_x, c_y, c_z]

assert(cross_product([2, 3, 4], [5, 6, 7]) == [-3, 6, -3])

11.22.10
...

Write a function replace(s, old, new) that replaces all occurrences of old with new in a string s:

test(replace("Mississippi", "i", "I") == "MIssIssIppI")

s = "I love spom! Spom is my favorite food. Spom, spom, yum!"
test(replace(s, "om", "am") ==
    "I love spam! Spam is my favorite food. Spam, spam, yum!")

test(replace(s, "o", "a") ==
    "I lave spam! Spam is my favarite faad. Spam, spam, yum!")

Hint: use the split and join methods.

Solution:

def replace(s, old, new):
    """Replaces all instances of old with new in a string s."""

    splitstring = s.split(old)
    outputstring = new.join(splitstring)
    return outputstring

That's a relatively explicit way of writing out the solution. Here's a more abbreviated version.

def replace(s, old, new):
    """Replaces all instances of old with new in a string s."""

    return new.join(s.split(old))

This page is released under the GNU Free Documentation License, any version 1.3 or later produced by the Free Software Foundation. I am grateful to the authors of the original textbook for releasing it that way: Peter Wentworth, Jeffrey Elkner, Allen B. Downey, and Chris Meyers.