Friday, December 23, 2011

Computational economics Lecture 7


Native Data Types

In Python, all objects have a type
>>> x = 1, 2
>>> type(x)
<type 'tuple'>
Later, we will learn how to build our own data types
But for now we will work with Python's existing (i.e., native) types
We have met floats, ints, strings, lists, tuples and bools
Let's review these types, and look a few more

Numeric data types

We have already met ints and floats
Here are a couple more

Long Integers

Typically, an int is stored with 32 bits of memory
Largest integer is therefore 2**32 / 2 - 1 = 2147483647
You can find the largest int on your machine via
>>> import sys
>>> sys.maxint
For integers larger than sys.maxint, Python uses long ints
  • Size is not limited, but algebraic operations are not as efficient
>>> x = 2**100
>>> x
1267650600228229401496703205376L
>>> type(x)
<type 'long'>

Complex Numbers

Python has a complex data type
>>> z = complex(1, 2)
>>> type(z)
<type 'complex'>
>>> z.real, z.imag
(1.0, 2.0)
>>> y = complex(2, 1)
>>> y * z
5j

Strings and String Formatting

String formatting is how we insert variables into a string
Here is a simple method
>>> x, y = 42, 24
>>> string = 'x = ' + str(x) + ' and y = ' + str(y)
>>> print string
x = 42 and y = 24
For more precision we can use Python's string formatting capabilities
x = 12.34701
print 'The price increased by %f percent' % x
The price increased by 12.347010 percent
Here f stands for float
Use i or d for integer
>>> print '%i' % 2
2
>>> print '%d' % 2
2
Use s for string
>>> print 'this is a %s' % 'string'
this is a string
Multiple values are inserted using a tuple
>>> stock = 'IBM'
>>> change = 10.2
>>> print 'the value of %s changed by %f percent' % (stock, change)
the value of IBM changed by 10.200000 percent
Floats are printed with 6 decimal places by default
This can be modified. For example:
>>> stock = 'IBM'
>>> change = 10.2
>>> print 'the value of %s changed by %.2f percent' % (stock, change)
the value of IBM changed by 10.20 percent

Dictionaries

One useful native data type we have not met is dictionaries

Introduction

Think of a list X as a map from 0,...,len(X)-1 to some objects
X = ['gozilla', 21, 'green']
  • 0 is mapped to 'godzilla'
    • X[0] == 'godzilla'
  • 1 is mapped to 21
    • X[1] == 21
  • 2 is mapped to 'green'
    • X[2] == 'green'
We can set up a more general mapping with a dictionary
>>> d = {'name': 'godzilla', 'age': 21, 'favorite color': 'green'}
>>> d['name']
'godzilla'
>>> d['age']
21
>>> d['favorite color']
'green'
>>> type(d)
<type 'dict'>
The strings 'name', 'age' and 'favorite color' are called the keys
The elements 'godzilla', 21 and 'green' are called the values
We can access them as follows:
>>> d.keys()
['age', 'name', 'favorite color']
>>> d.values()
[21, 'godzilla', 'green']
Like lists, dictionaries are mutable
>>> d2 = {1: 'a', 2: 'b'}  
>>> d2[1] = 'foo'  # Alter the value using the key
>>> d2
{1: 'foo', 2: 'b'}
The dictionary is modified in place (i.e., in memory, w/o creating new one)
Keys of a dictionary can be any immutable data type
>>> d2 = {[1, 2]: 'foo'}   # This is wrong
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> d2 = {(1, 2): 'foo'}  # But this is okay
Unlike lists, new elements can be inserted as follows
>>> d = {}  # An empty dictionary
>>> d[1] = 'foo'
>>> d
{1: 'foo'}
>>> d[2] = 'bar'
>>> d
{1: 'foo', 2: 'bar'}
For lists this fails
>>> X = []
>>> X[0] = 'foo'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

Working with Dictionaries

Often we want to loop through a dictionary
portfolio = {'IBM': 1000,
             'COP': 2000,
             'IPL': 500}

for k in portfolio.keys():
    print "You have %d shares in %s" % (portfolio[k], k)
An easier way to do this is
for k in portfolio:
    print "You have %d shares in %s" % (portfolio[k], k)
This works because dictionaries are "iterable"---we'll learn more about this later
A useful alternative is to the previous code is
for k, v in portfolio.items():
    print "You have %d shares in %s" % (v, k)
The items() method returns the key/value pairs as a list

Exercises

Problem:
Here is a coded message:
coded_message = "Olih#lv#wrr#lpsruwdqw#wr#eh#wdnhq#vhulrxvo|1"
And here is the map to decode it:
{'#': ' ',
 '1': '.',
 'O': 'L',
 'd': 'a',
 'e': 'b',
 'h': 'e',
 'i': 'f',
 'l': 'i',
 'n': 'k',
 'o': 'l',
 'p': 'm',
 'q': 'n',
 'r': 'o',
 's': 'p',
 'u': 'r',
 'v': 's',
 'w': 't',
 'x': 'u',
 '|': 'y'}
Using the map, decode the message:
Solution:
coded_message = "Olih#lv#wrr#lpsruwdqw#wr#eh#wdnhq#vhulrxvo|1"

code = {'#': ' ',
     '1': '.',
     'O': 'L',
     'd': 'a',
     'e': 'b',
     'h': 'e',
     'i': 'f',
     'l': 'i',
     'n': 'k',
     'o': 'l',
     'p': 'm',
     'q': 'n',
     'r': 'o',
     's': 'p',
     'u': 'r',
     'v': 's',
     'w': 't',
     'x': 'u',
     '|': 'y'}

decoded_message = ''

for character in coded_message:
    decoded_message = decoded_message + code[character]

print decoded_message

0 comments: