15-112: Fundamentals of Programming and Computer Science
Class Notes: Funtions Redux + Web and File I/O



# Here is the code from lecture.
# Any of this is fair game for the final exam!

import os

def smileyPrint(filename):
    with open(filename, "rt") as f:
       for line in f:
       print ":)", line,

smileyPrint("sample.txt")

def readFile(filename, mode="rt"):       # rt = "read text"
    with open(filename, mode) as fin:
        return fin.read()

def writeFile(filename, contents, mode="wt"):    # wt = "write text"
    with open(filename, mode) as fout:
        fout.write(contents)

def copyWithSmilies(source, destination):
  with open(source, "rt") as infile:
    with open(destination, "wt") as outfile:
      for line in infile:
        outfile.write(":) " + line)

copyWithSmilies("sample.txt", "smilies.txt")

import os
for file in os.listdir("."):  # "." (dot) means the current directory
  if ((len(file) > 4) and (file[-4:] == ".txt")):
    print "TEXT FILE: ", file
    print "I'm going to SMILEY it"
    smileyPrint(file)

import contextlib # for urllib.urlopen()
import urllib

def readWebPage(url):
    assert(url.startswith("http://"))
    with contextlib.closing(urllib.urlopen(url)) as fin:
        return fin.read()

print readWebPage("http://www.cs.cmu.edu/~112/")[0:1024]

def testWebIO():
    url = "http://www.kosbie.net/cmu/spring-13/15-112/handouts/celery.html"
    print "Reading from:", url
    html = readWebPage(url)
    print "#####################################"
    print "html:"
    print html
    print "#####################################"
    # now let's extract the joke
    startToken = '"KonaBody">'
    joke = html[html.find(startToken) + len(startToken) + 2 : ]
    joke = joke[ 0 : joke.find("</div>")]
    joke = joke.replace("<br>","").replace("\t"," ").replace("\r","")
    print "Celery, by Ogden Nash:"
    print joke
    print "#####################################"

help(max)


def isNumeric(n):
    """Returns True if n is a numeric type, and False otherwise."""
    return type(n) in (int, long, float, complex)

help(isNumeric)

>>> print isNumeric.__doc__

# Variable length args
def longestWord(*args):
    if (len(args) == 0): return None
    result = args[0]
    for word in args:
        if (len(word) > len(result)):
            result = word
    return result

print longestWord("this", "is", "really", "nice") # really

 mywords = ["this", "is", "really", "nice"]
>>> longestWord(mywords)
['this', 'is', 'really', 'nice']


>>> longestWord(*mywords)

def isProfessor(lastname):
    someProfs = ['kosbie', 'andersen', 'stehlik']
    return lastname in someProfs

def getNames(filterfunc, names):
    return [name for name in names if filterfunc(name)]

def demoIterNames():
    nameList = ['jordan', 'anqi', 'rudina', 'kosbie', 'andersen', 'kevin-was-here']
    for name in getNames(isProfessor, namelist):
      print name, "is a professor"

def isShortName(name):
    return len(name) <= 6

def demoShortNames():
    nameList = ['jordan', 'anqi', 'rudina', 'kosbie', 'andersen', 'kevin-was-here']
    for name in getNames(isShortName, nameList):
      print name, "is a short name"

def getMyNames():
  def isShortName(name):
    return len(name) <= 6
  
  nameList = ['jordan', 'anqi', 'rudina', 'kosbie', 'andersen', 'kevin-was-here']
  
  print getNames(isShortName, nameList)

print getNames(lambda name: (len(name) <= 6), nameList)

def getMyNames():
    nameLen = 6
    print getNames(lambda name: (len(name) <= nameLen))
    

# Capture
def getMyNames():
    nameList = ['jordan', 'anqi', 'rudina', 'kosbie', 'andersen', 'kevin-was-here']
    nameLen = 6
    nameFilter = lambda name: (len(name) <= nameLen)
    print getNames(nameFilter, nameList)
    nameLen = 5000
    print getNames(nameFilter, nameList)  # Is this going to return the same as before or all?

f = lambda x:  print x   # syntax error!

def makeAdderFn(delta):
    def f(x):
        return x + delta
    return f

add3 = makeAdderFn(3)
add4 = makeAdderFn(4)

print add3(5) # 8
print add4(5) # 9

# once again, with a lambda function

def makeAdderFn(delta):
    return lambda x : x + delta

add3 = makeAdderFn(3)
add4 = makeAdderFn(4)

print add3(5) # 8
print add4(5) # 9

for i in xrange(5):
    print i,

def simplexrange(upto):
    n = 0
    while n < upto:
        yield n
    n += 1

for i in simplexrange(5):
    print i,

def isProfessor(lastname):
    return lastname in ['kosbie', 'andersen', 'stehlik']

def iterNames(filterfunc, nameList):
    for name in nameList:
      if filterfunc(name):
     yield name

def demoIterNames():
    nameList = ['jordan', 'anqi', 'rudina', 'kosbie', 'andersen', 'kevin-was-here']

    for name in iterNames(isProfessor, nameList):
      print name, "is a professor"

################ Lab ##################

def getData():  ## WRITE ME
    url = "http://www.cs.cmu.edu/~dga/UScolleges93.csv"
    with contextlib.closing(urllib.urlopen(url)) as fin:
        with open("colleges.csv", "wt") as fout:
            for line in fin:
                fout.write(line)
    # Write me to colleges.csv

import os
import csv

def printARow(filename):
    with open(filename, "rt") as f:
        for row in csv.DictReader(f):
            print row["College Name"]

def findACollege(filename, checkFunc):
    with open(filename, "rt") as f:
        for row in csv.DictReader(f):
            if checkFunc(row):
                return row

def iterateColleges(filename, checkFunc):
    # yield

def findExpensive(r):
    t = r["out-of-state tuition"]
    if (len(t) > 0 and int(t) > 15000):
        return True
    return False

for r in iterateColleges("colleges.csv", findExpensive):
    print r["College Name"], r["out-of-state tuition"]

r = findACollege("colleges.csv", findCMU)
print r["out-of-state tuition"], r["College Name"]