920 likes | 1.33k Vues
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:. Dictionaries and Classes. Week 9:. Week 13:. Projects. Week 10:. Week 14:. dictionaries.
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: Dictionaries and Classes Week 9: Week 13: Projects Week 10: Week 14: dictionaries You're saying that Python's got class?
Tomorrow's HW Problem #1: Project idea Key! This is NOT the final project! This just a chance to create an assignment of your own!
Tomorrow's HW Problem #1: Project idea Key! This is NOT the final project! This just a chance to create an assignment of your own! • If you want to try something out, suggest something! • I'd be excited to help put together a feasible plan for a two-week pair of assignments: • first half would be due on 11/2 • final version would be due 11/9 Then you could reassess to see if you'd like to continue...
Tomorrow's HW Problem #1: Project idea ideas? Image-salon web application Google maps application https://www.cs.hmc.edu/twiki/bin/ view/CS5/GoogleMapsPart1
Thanks to Alex Hagen ! Do it yourself data-structures...
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… Whoa – how many elements are in these lists?
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 ] >>> 1986 ind True >>> 1969 ind False >>> d.pop( 1985 ) 'ox' get all keys check if a key is present delete a key (and its value) And if it's not present?
A challenge… states = { 'CA': 0, … } def stateChallenge( states ): """ states is a dictionary of the US western states -- the challenge is to name them all! """ whileTrue: guess = raw_input("Name a western state: ") if guess in states == False: print 'Try again...' elif states[guess] == 0: print 'Yes!' states[guess] += 1 else: print 'Already guessed...' print 'Phew!' help?!
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 person in Tree: 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 """
def favChild( person, Tree ): if person in Tree: 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…
Two other problem options HW6, Problem 4: the Mandelbrot set HW6, Problem 1: pi from pie!
Easy as p (1,1) Visualize: Pie (-1,-1)
Loops: for or while? pi_one(e) e == how close to π we need to get pi_two(n) n == number of darts to throw Which function will use which kind of loop?
Lab 9: the Mandelbrot Set Consider the following update rule for all complex numbers c: z0 = 0 zn+1 = zn2 + c If c does not diverge, it's in the M. Set. Benoit M. Nov. 20, 1924 – Oct. 14, 2010 Imaginary axis z3 c z2 z1 z4 Real axis z0
Lab 9: the Mandelbrot Set Consider the following update rule for all complex numbers c: z0 = 0 zn+1 = zn2 + c If c does not diverge, it's in the M. Set. Benoit M. Nov. 20, 1924 – Oct. 14, 2010 Imaginary axis z3 c z2 z1 z4 z0 Real axis example of a non-diverging cycle in blue
Lab 9: the Mandelbrot Set Consider the following update rule for all complex numbers c: z0 = 0 zn+1 = zn2 + c The shaded area are points that do not diverge.
Python and images from cs5png import * for creating and saving images Eco-friendly pngs! image = PNGImage( 300, 200 ) creates a bitmap object and names it image What might the inputs be for?
Python and images from cs5png import * for creating and saving images Eco-friendly pngs! image = PNGImage( 300, 200 ) creates a bitmap object and names it image inputs are height, width objects are software abstractions containing structured information