py_adv_feat_solutions-checkpoint


quant-econ Solutions: More Language Features

Exercise 1

Here's the standard solution


In [9]:
def x(t):
    if t == 0:
        return 0
    if t == 1:
        return 1
    else:
        return x(t-1) + x(t-2)

Let's test it


In [11]:
print [x(i) for i in range(10)]


[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Exercise 2

One solution is as follows


In [4]:
def column_iterator(target_file, column_number):
    """A generator function for CSV files.
    When called with a file name target_file (string) and column number 
    column_number (integer), the generator function returns a generator 
    which steps through the elements of column column_number in file
    target_file.
    """
    f = open(target_file, 'r')
    for line in f:
        yield line.split(',')[column_number - 1]
    f.close()

dates = column_iterator('test_table.csv', 1) 

i = 1
for date in dates:
    print date
    if i == 10:
        break
    i += 1


Date
2009-05-21
2009-05-20
2009-05-19
2009-05-18
2009-05-15
2009-05-14
2009-05-13
2009-05-12
2009-05-11

Exercise 3

Let's save the data first


In [6]:
%%file numbers.txt
prices
3
8

7
21


Writing numbers.txt

In [7]:
f = open('numbers.txt')

total = 0.0 
for line in f:
    try:
        total += float(line)
    except ValueError:
        pass

f.close()

print total


39.0

In [ ]: