Friday, December 23, 2011

Computational economics lecture 8


Built-In Functions

We have already met some of the built-in functions
  • Actions on sequences
    • min()max()len()
  • Type conversion
    • int()float()str()
  • Others
    • type()sum()input()raw_input()
Let's discuss a few more

File I/O

First we look at some built-in functions for file input/output
All these functions are for operating on text files

Opening and Reading Files

Suppose I have a file test.txt in the current working directory
Contents of the file is
Foo foo
Bar bar
I can read this in using the built-in function open():
>>> f = open('test.txt', 'r')
>>> text = f.read()
>>> text
'Foo foo\nBar bar\n'
>>> print text
Foo foo
Bar bar
>>> f.close()
The arguments of open() are the filename and I/O type (here it's r for read)
A call to open() returns a file object
>>> f = open('test.txt', 'r')  # Bind f to a new file object
>>> type(f)
<type 'file'>
Just as lists, strings, etc. have methods, so do file objects
  • The read() method returns the whole file as a single string
  • The close() method closes the connection to the file (writes buffered data, etc.)

Paths

Note that if test.txt is not in current directory then open() fails
In the next example, test.txt is in /tmp
>>> import os
>>> os.getcwd()   # Current directory is my home directory
'/home/john'
>>> f = open('test.txt', 'r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'test.txt'
In this case I have two choices
  • Specify the full path to the file
>>> f = open('/tmp/test.txt', 'r')  # This call succeeds
  • Or, change the current working directory to /tmp
>>> os.chdir('/tmp')
>>> f = open('test.txt', 'r')
It will be different on Windows/Mac, but I'm sure you can figure it out.

The readline() Method

To read in individual lines use readline()
>>> f = open('test.txt', 'r')
>>> f.readline()
'Foo foo\n'
>>> f.readline()
'Bar bar\n'
>>> f.readline()     # Continues to return the empty string
''
To read all lines into a list of strings use readlines()
>>> f = open('test.txt', 'r')
>>> f.readlines()
['Foo foo\n', 'Bar bar\n']
Note the difference between read() and readlines()
Finally, we can step through the lines in a for loop as follows
>>> f = open('test.txt', 'r')
>>> for line in f:
...  print line
This looks a bit magical, but we'll learn how it works in the lecture on iterators

Writing to Files

In order to write to files, we use the write() method
>>> f = open('newfile.txt', 'w')   # Open for *writing* using 'w'
>>> f.write('jailbreak\n')
>>> f.write('by AC/DC\n')
>>> f.close()
>>> f = open('newfile.txt', 'r')   # Next I open for reading using 'r'
>>> print f.read()
jailbreak
by AC/DC
Be careful: if file.txt exists, then the call open('file.txt', 'w') will overwrite it

Other Built-Ins

Let's quickly mention some other useful built-in functions

all() and any()

Two useful built-in functions are any() and all()
Given a list or tuple X,
  • any(X) returns True if at least one element evaluates as true
    • Otherwise False
  • all(X) returns True if all elements evaluate as true
    • Otherwise False
>>> X = [False, True, True]
>>> all(X)
False
>>> any(X)
True
Elements don't need to be bools
>>> X = ['a', 'b', '']
>>> all(X)
False

zip() and enumerate()

These are built-in functions, mainly used for looping
  • zip() is for stepping through pairs from two sequences
countries = ['Japan', 'Korea', 'China']
cities = ['Tokyo', 'Seoul', 'Beijing']

for country, city in zip(countries, cities):
    print 'The capital of %s is %s' % (country, city)
  • enumerate() is for stepping through a sequence and its indicies
X = ['a', 'b', 'c']

for index, value in enumerate(X):
    print 'X[%i] = %s' % (index, value)
These two built-ins are used a lot, so please remember them

Exercises

Exercise 1
Given two numeric lists/tuples X and Y of equal length, compute their inner product. Use zip()
Exercise 2
Consider the polynomial


Let the list of coefficients be given by coeff = [1, 3, -2, 9, 0, 1]
Using enumerate(), evaluate the polynomial at x = 7

Solutions

Solution to Exercise 1
print sum([x * y for x, y in zip(X,Y)])
Incidentally, this also works
print sum(x * y for x, y in zip(X,Y))
Solution to Exercise 2
coeff = [1, 3, -2, 9, 0, 1]
x = 7 

print sum(a * x**i for i, a in enumerate(coeff))

0 comments: