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

Question 1: Merge Dictionaries

Implement the function merge_dict. The merge_dict function merges two dictionaries with the same keys together.

def merge_dict(d1, d2):
    """Returns a dictionary with two dictionaries merged together. You can assume that the same keys appear in both dictionaries.
    >>> data8 = {"midterms":1, "projects":3}
    >>> data100 = {"midterms":2, "projects":3}
    >>> combined_exams = merge_dict(data8, data100)
    >>> combined_exams
    {'midterms': 3, 'projects': 6}
    >>> sunday_orders = {"pizza": 3, "hot dogs": 2, "fries": 5}
    >>> monday_orders = {"pizza": 1, "hot dogs": 1, "fries": 8}
    >>> combined_orders = merge_dict(sunday_orders, monday_orders)
    >>> combined_orders
    {'pizza': 4, 'hot dogs': 3, 'fries': 13}
    """
    result_dict = {}
    for work in d1:
        result_dict[work] = d1[work] + d2[work]
    return result_dict

Use OK to test your code:

python3 ok -q merge_dict

Question 2: Polynomial

A polynomial function is a function with coefficients, variables and constants. A polynomial function is said to be the nth degree polynomial if there is a term in the function with the variable to the nth degree. For example, a 4th degree polynomial must contain the term x^4 with some coefficient multiplied to it.

Complete the function polynomial, which takes in a degree and a list of coefficients. The function should output the corresponding polynomial function.

Hint: the staff solutions is one line and uses lambda + a list comprehension.

def polynomial(degree, coeffs):
    """
    >>> fourth = polynomial(4, [3,6,2,1, 100])
    >>> fourth(3)   # 3*(3**4) + 6*(3**3) + 2*(3**2) + 1*(3**1) + 100
    526
    >>> third = polynomial(3, [2, 0, 0, 0])
    >>> third(4)   # 2*(4**3) + 0*(4**2) + 0*(4**1) + 0
    128
    """
    # Option 1
    return lambda x: sum([coeffs[i]*(x ** (degree - i)) for i in range(degree + 1)])
    # Option 2
    def poly_func(x):
        return sum([coeffs[i]*(x ** (degree - i)) for i in range(degree + 1)])
    return poly_func

Use OK to test your code:

python3 ok -q polynomial

Submit

Make sure to submit this assignment by running:

python3 ok --submit

Maps

This homework is shorter than normal homeworks in order to give you more time to work on the Maps project. Please get started on it early.