Solutions for http://quant-econ.net/python_advanced_features.html
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)]
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
Let's save the data first
In [6]:
%%file numbers.txt
prices
3
8
7
21
In [7]:
f = open('numbers.txt')
total = 0.0
for line in f:
try:
total += float(line)
except ValueError:
pass
f.close()
print total
In [ ]: