Solutions: You can find the file with solutions for all questions here.

Questions

Question 1: Nonzero

Write a function that takes in a list and returns the first nonzero entry.

def nonzero(lst):
    """ Returns the first nonzero element of a list

    >>> nonzero([1, 2, 3])
    1
    >>> nonzero([0, 1, 2])
    1
    >>> nonzero([0, 0, 0, 0, 0, 0, 5, 0, 6])
    5
    """
    for i in lst:
        if i != 0:
            return i

Use OK to test your code:

python3 ok -q nonzero

Question 2: Contains N

Write a function that takes in a list and a number, and returns whether or not the list contains the value n.

def has_n(lst, n):
    """ Returns whether or not a list contains the value n.

    >>> has_n([1, 2, 2], 2)
    True
    >>> has_n([0, 1, 2], 3)
    False
    >>> has_n([], 5)
    False
    """
    for elem in lst:
        if elem == n:
            return True
    return False

Use OK to test your code:

python3 ok -q has_n

Question 3: Deep List

Implement the function deep_list, which takes in a list, and returns a new list which contains only elements of the original list that are also lists. Use a list comprehension.

def deep_list(seq):
    """Returns a new list containing elements of the original list that are lists.

    >>> seq = [49, 8, 2, 1, 102]
    >>> deep_list(seq)
    []
    >>> seq = [[500], [30, 25, 24], 8, [0]]
    >>> deep_list(seq)
    [[500], [30, 25, 24], [0]]
    >>> seq = ["hello", [12, [25], 24], 8, [0]]
    >>> deep_list(seq)
    [[12, [25], 24], [0]]
    """
    return [n for n in seq if type(n) is list]

Use OK to test your code:

python3 ok -q deep_list

Question 4: Total Price

Implement the function total_price, which takes in a list of prices of individual products and needs to find the total price. Unfortunately, any product that is priced greater than or equal to $20 has a 50 percent tax, so include that in the final price.

Try to do this in one line!

Cast your final answer to an integer to avoid floating point precision errors. For example, if x contains your final answer, return int(x)!

def total_price(prices):
    """
    Finds the total price of all products in prices including a
    50% tax on products with a price greater than or equal to 20.
    >>> total_price([5, 20, 30, 7])
    87
    >>> total_price([8, 4, 3])
    15
    >>> total_price([10, 100, 4])
    164
    """
    return int(sum([x if x < 20 else 1.5*x for x in prices]))

Use OK to test your code:

python3 ok -q total_price

Question 5: arange

Implement the function arange, which behaves just like np.arange(start, end, step) from Data 8. You only need to support positive values for step.

def arange(start, end, step=1):
    """
    arange behaves just like np.arange(start, end, step).
    You only need to support positive values for step.

    >>> arange(1, 3)
    [1, 2]
    >>> arange(0, 25, 2)
    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
    >>> arange(999, 1231, 34)
    [999, 1033, 1067, 1101, 1135, 1169, 1203]

    """
    return [n for n in range(start, end, step)]

Use OK to test your code:

python3 ok -q arange

Question 6: Shopping - Tax

Let's write a function that transforms a shopping cart, which we will represent as a list of 3 element tuples, by adding a specified percent tax to the price of each item. We will then compute the cost of all our items including tax.

Shopping carts are represented like this:

[(item1, cost1, quantity1), (item2, cost2, quantity2), ..., (itemN, costN, quantityN)]

Implement tax(shopping_cart, percent) and sum(shopping_cart) so you can figure out how much you have to pay for all of your items.

def tax(shopping_cart, percent):
    """
    Adds a `percent` tax to each item's price in a shopping cart.

    >>> fruitCart = [("apple", 0.5, 3), ("banana", 0.25, 4)]
    >>> tax(fruitCart, 10)
    [('apple', 0.55, 3), ('banana', 0.275, 4)]

    >>> calCart = [("oski", 1000, 1), ("go", 1.25, 2), ("bears", 3.5, 2)]
    >>> tax(calCart, 100)
    [('oski', 2000.0, 1), ('go', 2.5, 2), ('bears', 7.0, 2)]
    """
    taxMultiplier = 1 + (percent / 100)
    return [(name, price * taxMultiplier, quantity) for (name, price, quantity) in shopping_cart]

Use OK to test your code:

python3 ok -q tax

Question 7: Shopping - Cart Sum

def cartSum(shopping_cart):
    """
    Sums a shopping cart returning a float.

    >>> fruitCart = [("apple", 0.5, 3), ("banana", 0.25, 4)]
    >>> taxedFruit = tax(fruitCart, 10)
    >>> cartSum(taxedFruit)
    2.75
    >>> calCart = [("oski", 1000, 1), ("go", 1.25, 2), ("bears", 3.5, 2)]
    >>> taxedCal = tax(calCart, 100)
    >>> cartSum(taxedCal)
    2019.0
    """
    return sum([price*quantity for (name, price, quantity) in shopping_cart])

Use OK to test your code:

python3 ok -q cartSum

Optional Practice Question

Question 8: Adding matrices

To practice, write a function that adds two matrices together using list comprehensions. The function should take in two 2D lists of the same dimensions. Try to implement this in one line!

def add_matrices(x, y):
    """
    >>> matrix1 = [[1, 3],
    ...            [2, 0]]
    >>> matrix2 = [[-3, 0],
    ...            [1, 2]]
    >>> add_matrices(matrix1, matrix2)
    [[-2, 3], [3, 2]]
    """
    return [[x[i][j] + y[i][j] for j in range(len(x[0]))]
                               for i in range(len(x))]

Use OK to test your code:

python3 ok -q add_matrices

Submit

Make sure to submit this assignment by running:

python3 ok --submit