####################################################### # FILE I/O: ####################################################### # File Input/Output in Python # Loads a text file into a single string # Parameters: # fileName: a string with the name of the file to be loaded # Returns a string def loadTextAsString(fileName): fileHandler = open(fileName, "rt") # rt stands for read text text = fileHandler.read() # read the entire file into a single string fileHandler.close() # close the file!!! return text # Loads a text file into a list of strings. Each string is one line of text. # Parameters: # fileName: a string with the name of the file to be loaded # Returns a list of strings def loadTextAsList(fileName): fileHandler = open(fileName, "rt") # rt stands for read text text = fileHandler.readlines() # read the entire file into a list # remember: readline() returns a string of the first line!! fileHandler.close() # close the file!!! return text # Saves a string into a file. # If the file already exists, it will be overwritten. # Parameters: # fileName: a string with the name of the file to be written # Returns None def saveText(text, fileName): fileHandler = open(fileName, "wt") # wt stands for write text fileHandler.write(text) # write the text fileHandler.close() # close the file # to overwrite a file, you need to open a new file handler to # move our "pointer" to the begining of the file # example: # Assume test.txt is empty. what will be printed at the end? FILE_1 = open("test.txt", "rt") text = FILE_1.read() s_1 = "Now you see me..." FILE_1 = open("test.txt", "wt") FILE_1.write(s_1) FILE_3 = open("test.txt", "wt") s_2 = "Now you don't." FILE_1.write(s_2) s_4 = "------------->" FILE_1 = open("test.txt", "wt") FILE_3.write(s_4) s_3 = " Did you catch that?" FILE_3.write(s_3) FILE_1.close() FILE_3.close() FINAL = open("test.txt", "rt") final = FINAL.read() print final FINAL.close() # answer: -------------> Did you catch that? ####################################################### # STRING METHODS: ####################################################### just go here and play around! http://docs.python.org/release/2.5.2/lib/string-methods.html ####################################################### # TUPLES: ####################################################### # Tuples (Immutable Lists): # - Syntax: (item1, item2, etc...) # - Immutability # - Single-Line Tuple-Swap: (a,b) = (b,a) # - Singleton: (a,) a = [1, 2, 3, 4] b = [5, 6, 7, 8] c = zip(a,b) print c # [(1, 5), (2, 6), (3, 7), (4, 8)] (A,B) = zip(*c) # strange syntax, but this unzips c print A # (1, 2, 3, 4) print B # (5, 6, 7, 8) print ((A == a) and (B == b)) # False print ((A == tuple(a)) and (B == tuple(b))) # True ######################################################## # LIST COMPREHENSIONS: ######################################################## # what will each of the following print? # (run to see) print [i for i in range(20) if i%2 == 0] nums = [1,2,3,4] fruit = ["Apples", "Peaches", "Pears", "Bananas"] print [(i,f) for i in nums for f in fruit] print [(i,f) for i in nums for f in fruit if f[0] == "P" if i%2 == 1] ######################################################## # DICTIONARIES: ######################################################## # small example: d = dict() # or {} d["fred"] = "555-1212" # phone number d["wilma"] = "555-3456" # phone number print d["fred"] # now fred and wilma get married, so... d["fred"] = d["wilma"] print d["fred"] # Properties of Dictionaries: # 1) Dictionaries Map Keys to Values # 2) Keys are Sets # --> Keys are unordered, unique, immutable # --> Dictionaries are efficient # 3) Values are Unrestricted # --> values may be mutable d = dict() a = [1,2] d["fred"] = a print d["fred"] a += [3] print d["fred"] # sees change in a! # but keys may not be mutable! # d[a] = 42 # TypeError: unhashable type: 'list' # Create a dictionary from a list of (key, value) pairs pairs = [("cow", 5), ("dog", 98), ("cat", 1)] d = dict(pairs) print d # prints {'dog': 98, 'cow': 5, 'cat': 1} # Iterate over all keys in d. For example: d = { "cow":5, "dog":98, "cat":1 } for key in d: print key, d[key] # len(d) -> Return the number of items (key-value pairs) in the dictionary d. # key in d -> Return True if d has a key key, else False. # key not in d -> Equivalent to not key in d. # get(key) -> Return the value for key if key is in the dictionary, else return None # del d[key] -> Remove d[key] from d. Raises a KeyError if key is not in the map. # write a function mostFrequent(a) that takes a list 'a' # and returns a map of each unique element in 'a' and # the number of times that element occured in 'a' def mostFrequent(a): d = dict() for ele in a: d[ele] = 0 if d[ele] == 0: for x in a: if x == ele: d[ele] += 1 return d def testMostFrequent(): print "testing mostFrequent()..." assert(mostFrequent([2,5,3,4,6,4,2,4,5]) == {2: 2, 3: 1, 4: 3, 5: 2, 6: 1}) assert(mostFrequent([0, 1, 2, 3, 4, 5]) == {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}) assert(mostFrequent(["a", "a", "b", "c", "d", "d"]) == {"a": 2, "b": 1, "c": 1, "d": 2}) assert(mostFrequent([]) == {}) assert(mostFrequent(["a", True, 15112, "we", "rock", "rock"]) == {"a": 1, True: 1, 15112: 1, "we": 1, "rock": 2}) print "passed!" testMostFrequent() ######################################################## # 2-D LISTS: ######################################################## # Try, and FAIL, to create a variable-sized 2d list rows = 3 cols = 2 a = [ [0] * cols ] * rows # Error: creates shallow copy # Creates one unique row, the rest are aliases! print "This SEEMS ok. At first:" print " a = ", a a[0][0] = 42 print "But see what happens after a[0][0]=42" print " a = ", a # write a function to correclty create a 2D list: # solution 1: def make2dList_1(rows, cols): a = [] for row in range(rows): a += [[0] * cols] return a # solution 2: using list comp. def make2dList_2(rows, cols): return [ ([0] * cols) for row in xrange(rows) ] # Getting 2d List Dimensions # Create an "arbitrary" 2d List a = [ [ 2, 3, 5] , [ 1, 4, 7 ] ] print "a = ", a # Now find its dimensions rows = len(a) cols = len(a[0]) print "rows =", rows print "cols =", cols # And now loop over every element # Here, we'll add one to each element, # just to make a change we can easily see for row in xrange(rows): for col in xrange(cols): # This code will be run rows*cols times, once for each # element in the 2d list a[row][col] += 1 # Finally, print the results print "After: a =", a