Download presentation
Presentation is loading. Please wait.
Published byWarren Maxwell Modified over 9 years ago
1
IS 313 Today Schedule Week 0: files dictionaries You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where we've been… Where we're going… Week 4: Week 5: Week 6: Week 8: Week 9: Week 10: Week 12: Week 13: Week 14: Projects and Networks Functions and Data Loops and language
2
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 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 Code Result
3
Tomorrow's HW Problem #1: Wandering... 25262728502423220 An overworked CGU student (S) leaves Starbucks after their “late-night” breakfast and, each moment, randomly stumbles toward campus (W) or toward home (E) CGUhome (E) (W) Starbucks Write a program to model and analyze! this scenario... S Once the student arrives at home or the classroom, the trip is complete. The program should then print the total number of steps taken. 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
4
Tomorrow's HW Problem #2: Life Evolutionary rules Everything depends on a cell’s eight neighbors red cells are alive white cells are empty 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) life "out there"... Keep going!
5
Thanks to Alex Hagen !
6
Files >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() In Python reading files is no problem… use split as needed…
7
Files >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() In Python reading files is no problem… opens the file and calls it f reads the whole file and calls it f use text.split() for a list of each raw word closes the file (closing Python does the same) use split as needed… for example, text.split( '\n' )
8
split >>> 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') Breaking up is easy to do… ! use split as needed… How many pieces will there be?
9
split >>> 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'] Breaking up is easy to do… ! use split as needed… 3 !
10
File writing… 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() is as simple as print ! opens the file for writing
11
File writing… 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() is as simple as print !
12
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
13
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. 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. >>> wordCount( 'a.txt' ) 8 def wordList( filename ): >>> wordList( 'a.txt' )
14
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' )
15
Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… L L[0]L[1] reference 5 42
16
Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… You can't choose what to name data. L[0], L[1], … L L[0]L[1] reference 5 42
17
Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… L[1985] = 'ox' You can't choose what to name data. You have to start at 0. L[0], L[1], … L L[0]L[1] reference 5 42 L[1986] = 'tiger'
18
Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… You can't choose what to name data. You have to start at 0. Some operations can be slow for big lists … L[0], L[1], … L L[0]L[1] reference 5 42 if 'tiger' in L: L[1985] = 'ox' L[1986] = 'tiger'
19
Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. It's a list where the index can be any immutable-type key. >>> d = {} >>> d[1985] = 'ox' >>> d[1986] = 'tiger' >>> d {1985: 'ox', 1986: 'tiger'} >>> d[1985] 'ox' >>> d[1969] key error This seems like the key to dictionaries' value…
20
>>> d = {} >>> d[1985] = 'ox' >>> d[1986] = 'tiger' >>> d {1985: 'ox', 1986: 'tiger'} >>> d[1985] 'ox' >>> d[1969] key error Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. It's a list where the index can be any immutable-type key. creates an empty dictionary, d This seems like the key to dictionaries' value… 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 !
21
More on dictionaries 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' They don't seem moronic to me! delete a key (and its value) check if a key is present get all keys
22
A family dictionary?
23
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 ?
24
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 ?
25
A functional family? def addChild( person, Tree, jr ): """ adds person's new child to Tree """ For example, >>> addChild( 'lisa', T, 'abejr' )
26
A challenge… def stateChallenge( states ): """ prov is a dictionary of the US western states -- the challenge is to name them all! """ while 0 in 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!' states = { 'CA': 0, … } help?!
27
Change this code so that it tells you how many times you've guessed the same province… 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...' first, for real provinces then, for incorrect guesses…
28
Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none. def favGChild( person, Tree ): GC = [] def favChild( person, Tree ): if Tree.has_key( person ): Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' our list of GChildren
29
Name that author… ?
31
Markov Model The text file: I like spam. I like toast and spam. I eat ben and jerry's ice cream too. Technique for modeling any sequence of natural data Each item depends on only the item immediately before it. The Model: 1st-order Markov Model
32
Markov Model { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], … 'ben' : The text file: I like spam. I like toast and spam. I eat ben and jerry's ice cream too. Technique for modeling any sequence of natural data Each item depends on only the item immediately before it. The Model: 1st-order Markov Model
33
Markov Model { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : The text file: I like spam. I like toast and spam. I eat ben and jerry's ice cream too. Technique for modeling any sequence of natural data Each item depends on only the item immediately before it. The Model:
34
Markov Model { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : ['like', 'like', 'eat'] The text file: I like spam. I like toast and spam. I eat ben and jerry's ice cream too. Technique for modeling any sequence of natural data Each item depends on only the item immediately before it. The Model: How to get to I?
35
Markov Model { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : ['like', 'like', 'eat'], '$' : ['I', 'I', 'I'], The text file: I like spam. I like toast and spam. I eat ben and jerry's ice cream too. Technique for modeling any sequence of natural data Each item depends on only the item immediately before it. The Model: sentence-starting string
36
Generative Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it. Generating text: 1) start with the '$' string A key benefit is that the model can generate feasible data! 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.
37
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.
38
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. Original text: I like spam. I like toast and spam. I eat ben and jerry's ice cream too.
39
Creating a Markov Model def createDictionary( fileName ):
40
Generating Markov text def generateText( d, n ): d is the dictionary, and n is the number of words to generate…
41
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 Many coinages: Shakespeare J. K. Rowling Active vocabulary estimates range from 10,000-60,000. Passive vocabulary estimates are much higher.
42
WMSCI 2005 http://pdos.csail.mit.edu/scigen/
43
WMSCI 2005 Randomly-generated submission accepted to WMSCI 2005 http://pdos.csail.mit.edu/scigen/ No end to the WMSCI emails…
44
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 Invention, not reinvention. creating new data structures
45
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.
46
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.
47
Using objects and classes: >>> d = dict() >>> 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 ] A particularly appropriate reference … two methods (functions) within all objects of class dictionary an example of the dictionary constructor
48
The CONSTRUCTOR … class dict: """ a dictionary class """ def __init__( self ): """ the CONSTRUCTOR """ # sets all of the data needed # there's no data here! Code Comments defines a new datatype called dict the constructor is named __init__ but is used via the class name It sets all the DATA MEMBERS of a new object the object is called self
49
The REPR … class dict: """ 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 Code 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
50
Do-it-yourself data structures! class: your own TYPE of data object: a variable of your own class type data members: data an object contains methods: functions an object contains benefits: encapsulation & abstraction Object-oriented programming Blueprint for an object variables of that type An object is alive, responsible, and intelligent. - C++ FAQs
51
Examples… Do reference libraries have library references? Python's class libraries… Graphics libraries http://docs.python.org/lib/ >>> f = urllib.urlopen( 'http://www.cs.hmc.edu/~dodds/IS313/HW/index.html' ) >>> text = f.read() >>> text[:50]
52
Objects An object is a data structure (like a list), except (1) Its data elements have names chosen by the programmer. (2) Data elements are chosen & organized by the programmer (3) An object can have behaviors built-in by the programmer. usually called "methods" instead of functions User-defined structures that become part of the language (at least locally…)
53
But Why ? Flexibility Reusability Abstraction ordinary data structures create-your-own write once, take anywhere worry once, use anywhere
54
Date This is a class. It is a user-defined datatype (that you'll build in Lab this week!) Are you asking what Date-a a Date needs? We want (or need) to represent lots of interacting calendar days The Problem The Design What data should be set in the constructor? What functionality will we need to support? d.dow() usually some, but not all, is known beforehand
55
Using Date s this is an object of type Date >>> d = Date(1,1,2008) >>> d 1/1/2008 this is a CONSTRUCTOR … What does it do? the repr esentation of a particular object of type Date >>> d.isLeapYear() True >>> d2 = Date(12,31,2007) >>> d2 12/31/2007 >>> d2.isLeapYear() False the isLeapYear method returns True or False. How does it know what year to check? How does it know to return False, instead of True in this case ?? Another object of type Date - again, via the constructor.
56
class Date: def __init__( self, m, d, y ): """ the Date constructor """ self.month = m self.day = d self.year = y def __repr__( self ): """ used for printing Dates """ s = "%02d/%02d/%04d" % (self.month, self.day, self.year) return s def isLeapYear( self ): The Date class Why is everyone so far away?!
57
>>> d = Date(1,1,2008) >>> d 1/1/2008 self These methods need access to the object that calls them >>> d.isLeapYear() True >>> d2 = Date(12,31,2007) >>> d2 12/31/2007 >>> d2.isLeapYear() False is the specific OBJECT THAT CALLS A METHOD These methods need access to the object that calls them Why not use d ?
58
a Leap of faith…. class Date: def __init__( self, mo, dy, yr ): (constructor) def __repr__(self): (for printing) def isLeapYear( self ): """ here it is """ if self.yr%400 == 0: return True if self.yr%100 == 0: return False if self.yr%4 == 0: return True return False How about a 4000-year rule?
59
Date objects are mutable >>> d = Date(1,1,2008) >>> d 01/01/2008 always created with the CONSTRUCTOR … >>> d.yesterday() >>> d 12/31/2007 >>> d.tomorrow() >>> d 01/01/2008 the yesterday method returns nothing at all. Is it doing anything? Some methods return a value; others (like this one) change the object that call it! d has changed! but only if we want them to be!
60
Date id s >>> d = Date(11,28,2007) >>> d 11/28/2007 >>> d2 = Date(11,29,2007) >>> d2 11/29/2007 What date is on your id ? What id is on your Date? >>> d == d2 >>> d2.yesterday() >>> d == d2 Will these be true or false? >>> d.equals( d2 )
61
Double Date >>> d2 = d >>> d 11/26/2007 >>> d.yesterday() >>> >>> d2 >>> d2 == d >>> d2.equals(d) Excuse me -- id s please! What happens here?
62
Using copy >>> d2 = d.copy() >>> d 11/25/2007 >>> d2 11/25/2007 >>> d.yesterday() >>> d2 >>> d2 == d But where does copy come from? What happens here?
63
class Date: def __init__( self, mo, dy, yr ): def __repr__(self): def isLeapYear(self): def copy(self): """ returns a DIFFERENT object w/same date! """ def equals(self, d2): """ returns True if they represent the same date; False otherwise """ Where are these TWO inputs coming from?
64
"Quiz" class Date: def isBefore(self, d2): """ True if self is before d2 """ if self.yr < d2.yr: return True if self.mo < d2.mo: return True if self.dy < d2.dy: return True return False def tomorrow(self): """ moves the date that calls it ahead 1 day """ DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31] Why is this method WRONG for the dates DIM might be helpful… This tomorrow method should not return anything. It just CHANGES the date object that calls it. 1/1/2008 11/27/2007 how might you fix this problem?
65
class Date: def isBefore(self, d2): """ True if self is before d2 """ if self.yr < d2.yr: return True if self.mo < d2.mo: return True if self.dy < d2.dy: return True return False What's wrong? Why is this method WRONG for the dates 1/1/2008 11/27/2007
66
class Date: def tomorrow(self): """ moves the date that calls it ahead 1 day """ DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31]
67
Add these methods to Date no computer required… Prof. Art Benjamin Lab today / yesterday copy(self) equals(self, d2) yesterday(self) tomorrow(self) addNDays(self, N) subNDays(self, N) isBefore(self, d2) isAfter(self, d2) diff(self, d2) dow(self) and use your Date class to analyze our calendar a bit…
68
Unusual calendar years…
69
Lab … and hw questions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.