690 likes | 1.08k Views
IS 313 Today. Schedule. Where we've been…. Week 0:. Week 4:. Functions and Data. Loops and language. Week 1:. Week 5:. Week 2:. Week 6:. files. Where we're going…. Week 8:. Week 12:. Projects and Networks. Dictionaries and Classes. Week 9:. Week 13:. Week 10:. Week 14:.
E N D
IS 313 Today Schedule Where we've been… Week 0: Week 4: Functions and Data Loops and language Week 1: Week 5: Week 2: Week 6: files Where we're going… Week 8: Week 12: Projects and Networks Dictionaries and Classes Week 9: Week 13: Week 10: Week 14: dictionaries You're saying that Python's got class?
Diamonds! >>> printStripedDiamond( 8, 'A', 'B' ) A A B A B A A B A B A B A B A A B A B A B A B A B A B A A B A B A B A B def printStripedDiamond( width, sym1, sym2): for row in range (width,-1,-1): nextSym = sym1 for col in range(width): if row <= col: print nextSym, if nextSym == sym1: nextSym = sym2 else: nextSym = sym1 else: print '', print Result Code
Tomorrow's HW Problem #1: Wandering Starbucks ... ... CGU home S (E) (W) 0 22 23 24 25 26 27 28 50 An overworked CGU student (S) leaves Starbucks after their “late-night” breakfast and, each moment, randomly stumbles toward campus (W) or toward home (E) Once the student arrives at home or the classroom, the trip is complete. The program should then print the total number of steps taken. Write a program to model and analyze! this scenario... rs() rwPos(s, nsteps) rwSteps(s, low, hi) take a random step of +1 or -1 take nsteps random steps starting at s take random steps starting at s until you reach either low or hi
Tomorrow's HW Problem #2: Life red cells are alive Evolutionary rules • Everything depends on a cell’s eight neighbors • Exactly 3 neighbors give birth to a new, live cell! • Exactly 2 or 3 neighbors keep an existing cell alive • Any other number of neighbors kill the central cell (or keep it dead) Keep going! white cells are empty life "out there"...
Files In Python reading files is no problem… >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() use split as needed…
Files In Python reading files is no problem… >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() opens the file and calls itf reads the whole file and calls itf usetext.split() for a list of each raw word use split as needed… for example, text.split( '\n' ) closes the file (closing Python does the same)
split Breaking up is easy to do… ! >>> text = f.read() 'This is a file.\nLine 2\nLast line!\n' >>> text.split() ['This', 'is', 'a', 'file.', 'Line', '2', 'Last', 'line!'] >>> text.split('\n') ['This is a file.', 'Line 2', 'Last line!', ''] >>> text.split('in') use split as needed… How many pieces will there be?
split Breaking up is easy to do… ! >>> text = f.read() 'This is a file.\nLine 2\nLast line!\n' >>> text.split() ['This', 'is', 'a', 'file.', 'Line', '2', 'Last', 'line!'] >>> text.split('\n') ['This is a file.', 'Line 2', 'Last line!', ''] >>> text.split('in') ['This is a file.\nL', 'e 2\nLast l', 'e!\n'] use split as needed… 3 !
File writing… is as simple as print ! f = file( 'newfile.txt', 'w' ) print >> f, "This is in the file" print >> f, "named newfile.txt" x = 42 print >> f, "My favorite number is", x f.close() opens the file for writing
File writing… is as simple as print ! f = file( 'newfile.txt', 'w' ) print >> f, "This is in the file" print >> f, "named newfile.txt" x = 42 print >> f, "My favorite number is", x f.close()
Try it! def wordCount( filename ): Write a function wordCount that counts the number of words in a file named filename and then returns the result. >>> wordCount( 'a.txt' ) 8
Try it! def wordCount( filename ): Write a function wordCount that counts the number of words in a file named filename and then returns the result. >>> wordCount( 'a.txt' ) 8 def wordList( filename ): >>> wordList( 'a.txt' ) Write a function wordList that reads filename and then it writes a new file named 'words.txt' which is a list of the words present, one per line.
Thought experiment… def wordChal( filename ): How could you get a count of the number of times that each different word was present in the file? >>> wordChal( 'a.txt' )
If I had a dictionary, I guess I could look up what it was! Lists vs. Dictionaries Lists are not perfect… reference 42 5 L L[0] L[1]
If I had a dictionary, I guess I could look up what it was! Lists vs. Dictionaries Lists are not perfect… reference 42 5 You can't choose what to name data. L L[0] L[1] L[0], L[1], …
If I had a dictionary, I guess I could look up what it was! Lists vs. Dictionaries Lists are not perfect… reference 42 5 You can't choose what to name data. L L[0] L[1] L[0], L[1], … You have to start at 0. L[1985] = 'ox' L[1986] = 'tiger'
If I had a dictionary, I guess I could look up what it was! Lists vs. Dictionaries Lists are not perfect… reference 42 5 You can't choose what to name data. L L[0] L[1] L[0], L[1], … You have to start at 0. L[1985] = 'ox' L[1986] = 'tiger' Some operations can be slow for big lists … if'tiger'in L:
This seems like the key to dictionaries' value… Lists vs. Dictionaries In Python a dictionaryis a set of key - value pairs. >>> d = {} >>> d[1985] = 'ox' >>> d[1986] = 'tiger' >>> d {1985: 'ox', 1986: 'tiger'} >>> d[1985] 'ox' >>> d[1969] key error It's a list where the index can be any immutable-typekey.
This seems like the key to dictionaries' value… Lists vs. Dictionaries In Python a dictionaryis a set of key - value pairs. >>> d = {} >>> d[1985] = 'ox' >>> d[1986] = 'tiger' >>> d {1985: 'ox', 1986: 'tiger'} >>> d[1985] 'ox' >>> d[1969] key error creates an empty dictionary,d 1985 is the key 'ox' is the value 1986 is the key 'tiger' is the value Anyone seen this before? Retrieve data as with lists… or almost ! It's a list where the index can be any immutable-typekey.
More on dictionaries They don't seem moronic to me! Dictionaries have lots of built-in methods: >>> d = {1985: 'ox', 1986: 'tiger'} >>> d.keys() [ 1985, 1986 ] >>> d.has_key( 1986 ) True >>> d.has_key( 1969 ) False >>> d.pop( 1985 ) 'ox' get all keys check if a key is present delete a key (and its value)
A family dictionary… T = {'abe' :['homer','herb'], 'jackie':['marge','patty','selma'], 'homer' :['hugo','bart','lisa','maggie'], 'marge' :['hugo','bart','lisa','maggie']} keys can be any immutable type values can be any type at all… T['abe'] How to get 'selma' from T?
A functional family? def favChild( person, Tree ): """ person is a name (a string) Tree is a dictionary of children returns person's favorite child """ if Tree.has_key( person ): Kids = Tree[person] Kids.sort() return Kids[0] else: return'no children' Who is favored ? Side effects ?
A functional family? For example, >>> addChild('lisa', T,'abejr') def addChild( person, Tree, jr ): """ adds person's new child to Tree """
A challenge… states = { 'CA': 0, … } def stateChallenge( states ): """ prov is a dictionary of the US western states -- the challenge is to name them all! """ while0in states.values(): guess = raw_input("Name a western state: ") if states.has_key( guess ) == False: print'Try again...' elif states[guess] == 0: print'Yes!' states[guess] += 1 else: print'Already guessed...' print'Phew!' help?!
Change this code so that it tells you how many times you've guessed the same province… • first, for real provinces • then, for incorrect guesses… def provinceChallenge( prov ): while'0'in prov.values(): guess = raw_input("Guess: ") if prov.has_key( guess ) == False: print'Try again...' elif prov[guess] == 0: print'Yes!' prov[guess] += 1 else: print'Already guessed...'
def favChild( person, Tree ): if Tree.has_key( person ): Kids = Tree[person] Kids.sort() return Kids[0] else: return'no children' Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none. def favGChild( person, Tree ): GC = [] our list of GChildren
Markov Model Technique for modeling any sequence of natural data 1st-order Markov Model Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: The Model:
Markov Model Technique for modeling any sequence of natural data 1st-order Markov Model Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], … 'ben' : The Model:
Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : The Model:
Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : ['like', 'like', 'eat'] The Model: How to get toI?
Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : ['like', 'like', 'eat'], '$': ['I', 'I', 'I'], The Model: sentence-starting string
Generative Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . A key benefit is that the model can generate feasible data! Generating text: 1) start with the '$'string 2) choose a word following '$', at random. Call it w 3) choose a word following w, at random. And so on… 4) If w ends a sentence, '$' becomes the next word.
Generative Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . A key benefit is that the model can generate feasible data! I like spam. I like spam. I like toast and jerry's ice cream too. Generating text: 1) start with the '$'string 2) choose a word following '$', at random. Call it w 3) choose a word following w, at random. And so on… 4) If w ends a sentence, '$' becomes the next word.
Generative Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . A key benefit is that the model can generate feasible data! I like spam. I like spam. I like toast and jerry's ice cream too. Original text: I like spam. I like toast and spam. I eat ben and jerry's ice cream too. Generating text: 1) start with the '$'string 2) choose a word following '$', at random. Call it w 3) choose a word following w, at random. And so on… 4) If w ends a sentence, '$' becomes the next word.
Creating a Markov Model def createDictionary( fileName ):
Generating Markov text d is the dictionary, and n is the number of words to generate… def generateText( d, n ):
Number of distinct words? Shakespeare used 31,534 different words and a grand total of 884,647 words counting repetitions (across his works) http://www-math.cudenver.edu/~wbriggs/qr/shakespeare.html Active vocabulary estimates range from 10,000-60,000. Passive vocabulary estimates are much higher. Many coinages: Shakespeare J. K. Rowling
WMSCI 2005 http://pdos.csail.mit.edu/scigen/
WMSCI 2005 http://pdos.csail.mit.edu/scigen/ Randomly-generated submission accepted to WMSCI 2005 No end to the WMSCI emails…
Software Engineering creating and composing functions Building atop the work of others… Insight into details, e.g., data storage and retrieval. loops and data handling creating new data structures Invention, not reinvention.
Classes & Objects An object-oriented programming language allows you to build your own customized types of variables. (1) A class is a type of variable. (2) An object is one such variable.
Classes & Objects An object-oriented programming language allows you to build your own customized types of variables. (1) A class is a type of variable. (2) An object is one such variable. There will typically be MANY objects of a single class.
Using objects and classes: A particularly appropriate reference … >>> d = dict() an example of the dictionary constructor >>> d['answer'] = 42 >>> dir(d) all of the data members and methods of the dictionary class (and thus the object d !) >>> d.keys() [ 'answer' ] >>> d.values() [ 42 ] two methods (functions) within all objects of class dictionary
The CONSTRUCTOR … Code classdict: """ a dictionary class """ def __init__( self ): """ the CONSTRUCTOR """ # sets all of the data needed # there's no data here! Comments the constructor is named __init__ but is used via the class name It sets all the DATA MEMBERS of a new object defines a new datatype called dict the object is called self
The REPR … Code classdict: """ a dictionary class """ def __repr__( self ): """ a grim method """ s = '{' for key in self.keys(): s += str(key) + ':' s += str( self[key] ) + ', ' s += '}' return s Comments this method is named __repr__ and it provides a string that will be used when printing the object being printed is called self the string to print gets returned
Object-oriented programming Do-it-yourself data structures! Blueprint for an object class: your own TYPE of data object: a variable of your own class type variables of that type data members: data an object contains methods: functions an object contains benefits: encapsulation & abstraction An object is alive, responsible, and intelligent. - C++ FAQs