Q4

Now we'll start working with some basic Python data structures.

A

In this question, you'll implement a cumulative product method. Given a list, you'll compute a list that's the same length, but which contains the cumulative product of the current number with all the previous numbers.

Assume the initial product is 1, and I provide a list with the numbers 2, 1, 4, and 3. I multiply my initial product (1) by 2, and put that new product into another list. Then I repeat: multiply my new product by the next element of the list (1), and store that new-new product (2) in the second list. Repeat again: multiply my new-new product (2) with the next number in the list (4), and store that new-new-new product (8) in the second list.

Example Input: [2, 1, 4, 3]

Example Output: [2, 2, 8, 24]


In [ ]:
def cumulative_product(start_list):
    out_list = []
    
    ### BEGIN SOLUTION
    
    ### END SOLUTION
    
    return out_list

In [ ]:
inlist = [89, 22,  3, 24,  8, 59, 43, 97, 30, 88]
outlist = [89, 1958, 5874, 140976, 1127808, 66540672, 2861248896, 277541142912, 8326234287360, 732708617287680]
assert set(cumulative_product(inlist)) == set(outlist)

inlist = [56, 22, 81, 65, 40, 44, 95, 48, 45, 26]
outlist = [56, 1232, 99792, 6486480, 259459200, 11416204800, 1084539456000, 52057893888000, 2342605224960000, 60907735848960000]
assert set(cumulative_product(inlist)) == set(outlist)

B

This time, you'll implement a method for computing the average value of a list of numbers. Remember how to compute an average: add up all the values, then divide that sum by the number of values you initially added together.

Example Input: [2, 1, 4, 3]

Example Output: 2.5


In [ ]:
def average(numbers):
    avg_val = 0.0
    
    ### BEGIN SOLUTION
    
    ### END SOLUTION
    
    return avg_val

In [ ]:
import numpy as np

inlist = np.random.randint(10, 100, 10).tolist()
np.testing.assert_allclose(average(inlist), np.mean(inlist))

inlist = np.random.randint(10, 1000, 10).tolist()
np.testing.assert_allclose(average(inlist), np.mean(inlist))

C

In this question, you'll write a method that takes a list of numbers [0-9] and returns a corresponding list with the "ordinal" versions. That is, if you see a 1 in the list, you'll create a string "1st". If you see a 3, you'll create a string "3rd", and so on.

Example Input: [2, 1, 4, 3, 4]

Example Output: ["2nd", "1st", "4th", "3rd", "4th"]


In [ ]:
def return_ordinals(numbers):
    out_list = []
    
    ### BEGIN SOLUTION
    
    ### END SOLUTION
    
    return out_list

In [ ]:
inlist = [5, 6, 1, 9, 5, 5, 3, 3, 9, 4]
outlist = ["5th", "6th", "1st", "9th", "5th", "5th", "3rd", "3rd", "9th", "4th"]
for y_true, y_pred in zip(outlist, return_ordinals(inlist)):
    assert y_true == y_pred.lower()

inlist = [7, 5, 6, 6, 3, 5, 1, 0, 5, 2]
outlist = ["7th", "5th", "6th", "6th", "3rd", "5th", "1st", "0th", "5th", "2nd"]
for y_true, y_pred in zip(outlist, return_ordinals(inlist)):
    assert y_true == y_pred.lower()