Lecture 2 continued

regular expressions

Provides a way to search text. Looking for matching patterns


In [39]:
import re
print all([
    not re.match("a","cat"),
    re.search("a","cat"),
    not re.search("c","dog"),
    3 == len(re.split("[ab]","carbs")),
    "R-D-" == re.sub("[0-9]","-","R2D2")
])  # prints true if all are true


True

Object-oriented programming

Creating classes of objects with data and methods(functions) that operate on the data.


In [40]:
class Set:
    def __init__(self, values=None):
        """This is the constructor"""
        self.dict={}
        if values is not None:
            for value in values:
                self.add(value)
    def __repr__(self):
        """Sting to represent object in class like a to_string function"""
        return "set:"+str(self.dict.keys())
    def add(self, value):
        self.dict[value] = True
    def contains(self, value):
        return value in self.dict 
        
    def remove(self,value):
        del self.dict[value]

In [41]:
#using the class
s = Set([1,2,3])
s.add(4)
s.remove(3)
print s.contains(3)


False

In [42]:
print s


set:[1, 2, 4]

Functional Tools

sometimes you want to change behavior based on the passed value types


In [43]:
def exp(base,power):
    return base**power

#exp(2,power)
def two_to_the(power):
    return exp(2,power)

print( two_to_the(3) )


8

In [19]:
def multiply(x,y): return x*y

products = map(multiply,[1,2],[4,5])
print products


[4, 10]

In [ ]:

enumerate

enumerates creates a tuple (index,element)


In [25]:
#example use
documents = ["a","b"]
def do_something(index,item):
    print "index:"+str(index)+" Item:"+item
    
for i, document in enumerate(documents):
    do_something(i,document)


index:0 Item:a
index:1 Item:b

In [29]:
def do_something(index ):
    print "index:"+str(index) 
    
for i, _ in enumerate(documents): do_something(i)


index:0
index:1

Zip and argument unpacking

zip forms two more more lists for other lists


In [30]:
list1 = ['a','b','c']
list2 = [1,2,3]
zip(list1,list2)


Out[30]:
[('a', 1), ('b', 2), ('c', 3)]

In [34]:
pairs = [('a', 1), ('b', 2), ('c', 3)]
letters, numbers = zip(*pairs)  #  * performs argument unpacking
print letters
print numbers


('a', 'b', 'c')
(1, 2, 3)

args and kwargs

higher order function support - functions on functions


In [35]:
def doubler(f):
    def g(x):
        return 2 * f(x)
    return g

def f1(x):
    return x+1

g= doubler(f1)

print g(3)


8

In [38]:
def magic(*args, **kwargs):
    print "unamed args", args
    print "Key word args", kwargs
    
magic(1,2,key1="word1",key2="word2")


unamed args (1, 2)
Key word args {'key2': 'word2', 'key1': 'word1'}

In [ ]: