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: Coordinates

Implement a function coords, which takes a function, a sequence, and an upper and lower bound on output of the function. coords then returns a list of x, y coordinate pairs (lists) such that:

  • Each pair contains [x, fn(x)]
  • The x coordinates are the elements in the sequence
  • Only pairs whose y coordinate is within the upper and lower bounds (inclusive)

See the doctests for examples.

One other thing: your answer can only be one line long. You should make use of list comprehensions!

def coords(fn, seq, lower, upper):
    """
    >>> seq = [-4, -2, 0, 1, 3]
    >>> def fn(x):
    ...     return x**2
    >>> coords(fn, seq, 1, 9)
    [[-2, 4], [1, 1], [3, 9]]
    """
    return [[x, fn(x)] for x in seq if lower <= fn(x) and f(x) <= upper]

Use OK to test your code:

python3 ok -q coords

Optional Practice Question

Question 7: 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