quant-econ Solutions: Python Essentials


In [2]:
from __future__ import division  # Omit for Python 3.x

Exercise 1

Part 1 solution:

Here's one possible solution


In [2]:
x_vals = [1, 2, 3]
y_vals = [1, 1, 1]
sum([x * y for x, y in zip(x_vals, y_vals)])


Out[2]:
6

This also works


In [3]:
sum(x * y for x, y in zip(x_vals, y_vals))


Out[3]:
6

Part 2 solution:

One solution is


In [4]:
sum([x % 2 == 0 for x in range(100)])


Out[4]:
50

This also works:


In [5]:
sum(x % 2 == 0 for x in range(100))


Out[5]:
50

Some less natural alternatives that nonetheless help to illustrate the flexibility of list comprehensions are


In [6]:
len([x for x in range(100) if x % 2 == 0])


Out[6]:
50

and


In [7]:
sum([1 for x in range(100) if x % 2 == 0])


Out[7]:
50

Part 3 solution

Here's one possibility


In [8]:
pairs = ((2, 5), (4, 2), (9, 8), (12, 10))
sum([x % 2 == 0 and y % 2 == 0 for x, y in pairs])


Out[8]:
2

Exercise 2


In [9]:
def p(x, coeff):
    return sum(a * x**i for i, a in enumerate(coeff))

In [10]:
p(1, (2, 4))


Out[10]:
6

Exercise 3

Here's one solution:


In [18]:
def f(string):
    count = 0
    for letter in string:
        if letter == letter.upper() and letter.isalpha():
            count += 1
    return count
f('The Rain in Spain')


Out[18]:
3

Exercise 4

Here's a solution:


In [22]:
def f(seq_a, seq_b):
    is_subset = True
    for a in seq_a:
        if a not in seq_b:
            is_subset = False
    return is_subset

# == test == #

print f([1, 2], [1, 2, 3])
print f([1, 2, 3], [1, 2])


True
False

Of course if we use the sets data type then the solution is easier


In [23]:
def f(seq_a, seq_b):
    return set(seq_a).issubset(set(seq_b))

Exercise 5


In [25]:
def linapprox(f, a, b, n, x):
    """
    Evaluates the piecewise linear interpolant of f at x on the interval 
    [a, b], with n evenly spaced grid points.

    Parameters 
    ===========
        f : function
            The function to approximate

        x, a, b : scalars (floats or integers) 
            Evaluation point and endpoints, with a <= x <= b

        n : integer
            Number of grid points

    Returns
    =========
        A float. The interpolant evaluated at x

    """
    length_of_interval = b - a
    num_subintervals = n - 1
    step = length_of_interval / num_subintervals  

    # === find first grid point larger than x === #
    point = a
    while point <= x:
        point += step

    # === x must lie between the gridpoints (point - step) and point === #
    u, v = point - step, point  

    return f(u) + (x - u) * (f(v) - f(u)) / (v - u)

In [ ]: