# Example code for Day 13 Lecture, CS 111 Spring 2014 # Thinking through references x = 4 y = x z = x print x, y, z y = 7 print x, y, z x = 8 print x, y, z # Can't modify arguments! def addOneToX(x): print "In the function, x is", x x = x + 1 print "In the function, after modifying, x is", x x = 6 print "Before the function call, x is", x addOneToX(x) print "After the function call, x is", x # But lists are mutable! What are the references now? P = ["how", "now", "brown", "cow"] print P print P[2] P[2] = "round" print P Q = P print Q P[1] = "plow" print P print Q Q[3] = "sow" print P print Q P = ["when", "then", "red", "hen"] print P print Q # The *reference* gets passed into a function def setOneToFive(x): print "In the function, x is", x x[1] = 5 print "After modifying, x is", x L = [7, 8, 9] print "Before calling the function, L is", L setOneToFive(L) print "After calling the function, L is", L ### Dictionaries! # Creating a dictionary and looking things up in it phonebook = {} phonebook['Andre'] = '310-886-1024' phonebook['Melissa'] = '757-318-2048' phonebook['Shawn'] = '718-593-4096' person = "Melissa" print "%s's number is %s" % (person, phonebook[person]) print type(phonebook) print phonebook # Counting words in a big text file # First we'll make a dictionary mapping each unique word in the text to the # number of times it occurs. # Once you understand this program, try replacing the first line with # f = open("carroll-alice_s_adventures_in_wonderland.txt", "r") f = open("alice_tiny.txt", "r") text = f.read().lower() f.close() counts = {} for token in text.split(): # Remove any unprintable characters or punctuation at the beginning or end. word = token.strip().strip('.!?-\'",;') print word if len(word) > 0: if not counts.has_key(word): counts[word] = 1 else: counts[word] += 1 # Now we've populated our dictionary. # What are the most common words? top_twenty_words = [] for i in range(20): # Find the most common word that we haven't recorded yet. max_count = 0 max_word = "" for word in counts.iterkeys(): if (word not in top_twenty_words) and (counts[word] > max_count): max_word = word max_count = counts[word] # Add the word and its count to our list. top_twenty_words.append(max_word) for word in top_twenty_words: print counts[word], word