1 / 109

IST 380 this week!

IST 380 this week!. Hw # 8 due 4 /9. Building classes. ... vs. using the library. hw8pr1. hw8pr2. file and dictionary classes. The Date class. files. dictionaries. If I had a dictionary, I guess I could look up what it was!. IST 380 this week !. Hw #7 due 4 /2. Analyzing lists….

aimee
Download Presentation

IST 380 this week!

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IST380 this week! Hw#8due 4/9 Building classes... ... vs. using the library hw8pr1 hw8pr2 file and dictionary classes The Date class files dictionaries If I had a dictionary, I guess I could look up what it was!

  2. IST380 this week! Hw#7 due 4/2 Analyzing lists… 2d simulations! hw7pr1 hw7pr2 TheTT Securities problem TheGame of Life problem I think What's App employees just won that game!

  3. Last couple of weeks… (!) Bay area!

  4. Last couple of weeks… (!) Bay area!

  5. Last couple of weeks… (!) CS tourism!

  6. Last couple of weeks… (!) 28% bored I think it's the 28% of the time that the instructor goes on irrelevant tangents about recent travels!!

  7. Part 1: programs with class Building classes... ... vs. using the library hw8pr1 hw8pr2 file and dictionary classes The Date class files dictionaries If I had a dictionary, I guess I could look up what it was!

  8. What's all this about class? A bird's-eye view! Data Functions Loops and List comprehensions Designing Data! The Dateclass whose convenience? Theory & practice

  9. Classes and Objects

  10. Everythingin Python is an object! Its capabilities depend on its class. functions type "methods" what's more, you can build your own...

  11. Everything is an object? Take strings, for example: >>> s = str( 42 ) >>> type(s) <type 'str'> >>> dir(s) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] This calls the strconstructor. Shows the type of s is str Shows all of the methods (functions) of s Let's try some!

  12. Objects Like a list, an object is a container, but much more customizable: (1) Its data elements have names chosen by the programmer. (2) An object contains its own functions, called methods (3) In its methods, objects refer to themselves as self (4) Python signals special methods with two underscores: __init__ is called the constructor; it creates new objects __repr__ tells Python how to print its objects I guess we should doubly underscore these two methods!

  13. ADateobject, d d 31 3 2014 month day year memory location ~ 42042778

  14. ADateobject, d d 31 3 2014 month day year memory location ~ 42042778

  15. classDate: """ a blueprint (class) for objects that represent calendar days """ def__init__( self, mo, dy, yr ): """ the Date constructor """ self.month = mo self.day = dy self.year = yr TheDateclass This is the start of a new type called Date It begins with the keyword class This is the constructor for Date objects As is typical, it assigns input data to the data members. These are data members – they are the information inside every Date object.

  16. Cool dates! 11/12/13

  17. Date This is a class. It is a user-defined datatype that you'll build in hw8this week… add a print statement to see that this is OUR OWN code… >>> d = Date(11,12,2013) >>> d.month 11 >>> d.day 12 Constructor! d contains data members named day, month, and year >>> d 11/12/2013 The repr! the representation of an object of type Date The isLeapYear method returns True or False. How does it know what year to check? >>> d.isLeapYear() True

  18. classDate: """ a blueprint (class) for objects that represent calendar days """ def__init__( self, mo, dy, yr ): """ the Date constructor """ self.month = mo self.day = dy self.year = yr def__repr__( self ): """ used for printing Dates """ s = "%02d/%02d/%04d" % (self.month, self.day,self.year) return s The Dateclass Why is everyone so far away?! This is the reprfor Date objects It tells Python how to print these objects. Why self instead of d ?

  19. self is the variable calling a method >>> d = Date(11,12,2013) >>> d 11/12/2013 >>> d.isLeapYear() False These methods need access to the object that calls them: it's self >>> d2= Date(1,1,2016) >>> d2 01/01/2016 >>> d2.isLeapYear() True

  20. classDate: """ a blueprint (class) for objects that represent calendar days """ def__init__( self, mo, dy, yr ): """ the Date constructor """ self.month = mo self.day = dy self.year = yr def__repr__( self ): """ used for printing Dates """ s = "%02d/%02d/%04d" % (self.month, self.day,self.year) return s defisLeapYear( self ): """ anyone know the rule? """ The Dateclass Why is everyone so far away?! which are leap years?

  21. class Date: def __init__( self, mo, dy, yr ): (constructor) def __repr__(self): (for printing) defisLeapYear( self ): """ here it is """ if self.year%400 == 0: return True if self.year%100 == 0: return False if self.year%4 == 0: return True return False

  22. == vs. equals UFO license Area 51, CA What id is on your Date? >>> d = Date(11,12,2013) >>> d 11/12/2013 >>> d2 = Date(11,12,2012) >>> d2 11/12/2013 this constructs a different Date Python objects are handled by reference… == compares references! >>> d ==d2 False How can this be False ?

  23. TwoDateobjects: d 12 11 2013 month day year memory location ~ 42042778 == compares memory locations, not contents originals underneath…

  24. == vs. equals UFO license Area 51, CA What date is on your id? What id is on your Date? >>> d = Date(11,12,2013) >>> d 11/12/2013 >>> d2 = Date(11,12,2013) >>> d2 11/12/2013 this constructs a different Date Python objects are handled by reference… .equals compares contents >>> d.equals(d2) True

  25. Date >>> d = Date(12,31,2013) >>> d 12/31/2013 always create with the CONSTRUCTOR … the tomorrow method returns nothing at all. Is it doing anything? >>> d.tomorrow() >>> d 01/01/2014 >>> d.subNDays(50) lots of printing, but no return value! d has changed! Why is this important? Some methods return a value; others change the object that call it!

  26. hw8, problem1 Add these to your Dateclass! yesterday(self) tomorrow(self) addNDays(self, N) subNDays(self, N) isBefore(self, d2) isAfter(self, d2) diff(self, d2) dow(self) Prof. Benjamin ! no computer required… and use your Dateclass to analyze our calendar a bit…

  27. class Date: def __init__( self, mo, dy, yr ): def __repr__(self): defisLeapYear(self): defequals(self, d2): """ returns True if they represent the same date; False otherwise """ if return True else: return False equals How many Dates are here? Which one is selfish? plain approach

  28. class Date: def __init__( self, mo, dy, yr ): def __repr__(self): defisLeapYear(self): defequals(self, d2): """ returns True if they represent the same date; False otherwise """ if return True else: return False equals How many Dates are here? Which one is selfish? list approach!

  29. Try it! class Date: deftomorrow(self): """ moves the date ahead 1 day """ DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31] Implement tomorrow ! Don't return anything. This CHANGESthe date object that calls it. DIM looks pretty bright to me! first, add 1 to self.day then, adjust the month and year, only if needed Let's do this on the board… Extra: how could you make this work in leap years!?

  30. a thought experiment… class Date: defisBefore(self, d2): """ True if self is before d2, else False """ ifself.year < d2.year: returnTrue ifself.month < d2.month: returnTrue ifself.day < d2.day: returnTrue return False (1) There's a bug here – what is it!? >>> d = Date(1,1,2014) >>> d2 = Date(11,12,2013) >>> d.isBefore( d2 ) True (2) How could we fix it? Bug!

  31. plain approach class Date: defisBefore(self, d2): """ if self is before d2, this should return True; else False """ ifself.year < d2.year: return True ifself.year> d2.year: return False # here, the years are EQUAL! ifself.month < d2.month:returnTrue ifself.month> d2.month: return False # here, the years and months are EQUAL! ifself.day < d2.day:return True return False

  32. list approach?! class Date: defisBefore(self, d2): """ if self is before d2, this should return True; else False """ self_list = [self.year,self.month,self.day] d2_list = [d2.year,d2.month,d2.day] if returnTrue else: returnFalse I want even LESS !

  33. class Date: deftomorrow(self): """ moves the date ahead 1 day """ DIM = [0,31,fdays,31,30,31,30,31,31,30,31,30,31] self.day += 1 # add 1 to the day! ifself.day > DIM[self.month]: # check day self.month += 1 self.day = 1 ifself.month > 12: # check month self.year += 1 self.month = 1 better as a variable!

  34. class Date: deftomorrow(self): """ moves the date ahead 1 day """ fdays= 28 + self.isLeapYear() # What ?! DIM = [0,31,fdays,31,30,31,30,31,31,30,31,30,31] self.day += 1 ifself.day > DIM[self.month]: self.month += 1 self.day = 1 ifself.month > 12: self.year += 1 self.month = 1

  35. Not all years are equals!

  36. Part 2: files + dictionaries! Building classes... ... vs. using the library hw8pr1 hw8pr2 file and dictionary classes The Date class files dictionaries If I had a dictionary, I guess I could look up what it was!

  37. Files! In Python reading files is no problem… >>> f = open( 'a.txt' ) >>> text = f.read() >>> f.close() >>> text 'I like poptarts and 42 and spam.\nWill I >>> LoW = text.split() [ 'I', 'like', 'poptarts', ... ] opens the file and calls it f reads the whole file into the string text closes the file (optional) text.split()returns a list of each "word"

  38. defword_count( filename ): """ word-counting program """ f = open( filename ) text = f.read() f.close() LoW = text.split() print "There are", len(LoW), "words." file handling word counting Let's try this! Files are fun (and hugely powerful!) What if we wanted the number of different words in the file? This would be the author's vocabulary size, instead of the total word count.

  39. This seems like the key to dictionaries' value… Dictionaries >>> d = {} >>> d[1994] = 'dog' >>> d[1995] = 'pig' >>> d {1995:'dog', 1994:'pig'} >>> d[1995] 'pig' creates an empty dictionary,d 1994 is the key 'dog' is the value 1995is the key 'pig'is the value key value Adictionaryis a set of key - valuepairs Curly! And colony!

  40. More on dictionaries They don't seem moronic to me! Strings can be keys, too! >>> d = {'pig': 1995, 'dog': 1994} >>> 'dog'in d >>> 'cat'in d True False >>> len(d) 2 >>> d.keys() [ 'pig','dog' ] >>> d.values() [ 1994, 1995] >>> d.items() [ ('dog', 1994), ('pig', 1995) ] inchecks if a key is present len ()returns the # of keys d.keys()returns a list of all keys d.values ()returns a list of all values d.items ()returns a list of all key, value pairs

  41. defvocab_count( filename ): """ vocab-counting program """ f = open( filename ) text = f.read() f.close() LoW = text.split() print "There are", len(LoW), "words." d = {} for wdin LoW: if wdnot in d: d[wd] = 1 else: d[wd] += 1 print"There are", len(d), "distinct words.\n" return d # this way we can use the data in d later! file handling word counting Tracking the number of occurences of each word with a dictionary, d.

  42. Vocabulary, anyone? Shakespeare used 31,534 different words -- and a grand total of 884,647 words -- counting repetitions (across all of his works) http://www-math.cudenver.edu/~wbriggs/qr/shakespeare.html Shakespearean coinages gust besmirch unreal superscript watchdog swagger affined rooky attasked out-villianed There's one contemporary author in the Oxford English Dictionary… Who? What word? successful unsuccessful http://www.pathguy.com/shakeswo.htm http://www.shakespeare-online.com/biography/wordsinvented.html

  43. Vocabulary, anyone? Shakespeare used 31,534 different words -- and a grand total of 884,647 words -- counting repetitions (across all of his works) http://www-math.cudenver.edu/~wbriggs/qr/shakespeare.html Shakespearean coinages There's one contemporary author in the Oxford English Dictionary… gust besmirch unreal superscript watchdog swagger affined rooky attasked out-villianed There's one contemporaryauthor in the Oxford English Dictionary… Who? What word? successful unsuccessful http://www.pathguy.com/shakeswo.htm http://www.shakespeare-online.com/biography/wordsinvented.html

  44. Vocabulary, anyone? Shakespeare used 31,534 different words -- and a grand total of 884,647 words -- counting repetitions (across all of his works) http://www-math.cudenver.edu/~wbriggs/qr/shakespeare.html J. K. Rowling ! Shakespearean coinages gust besmirch unreal superscript watchdog swagger affined rooky attasked out-villianed successful unsuccessful http://www.pathguy.com/shakeswo.htm http://www.shakespeare-online.com/biography/wordsinvented.html

  45. Algorithmic authoring?

  46. MarkovModels Techniques for modeling any sequence of natural data speech, text, sensor data... 1st-order Markov Model (its defining property) Each item depends only on the one immediately before it .

  47. Our Markov Model Original file: Markov Model: { '$': ['I', 'Will', 'I'], 'I': ['like', 'get', 'like'] 'like': ['poptarts', 'spam'], 'poptarts': ['and', 'for'], 'and': '42': ['and'], 'Will': ['I'], 'the': 'spam': ['and', 'poptarts!'], 'get': ['spam'], 'for': ['the'] A dictionary! What are the keys? What are the values? What are the missing values? What is the '$'? Why do some keys seem missing? }

  48. Our Markov Model Original file: I like poptarts and 42 and spam. Will I get spam and poptarts for the holidays? I like spam poptarts! Markov Model: { '$': ['I', 'Will', 'I'], 'I': ['like', 'get', 'like'] 'like': ['poptarts', 'spam'], 'poptarts': ['and', 'for'], 'and': ['42', 'spam.', 'poptarts'], '42': ['and'], 'Will': ['I'], 'the': ['holidays?'], 'spam': ['and', 'poptarts!'], 'get': ['spam'], 'for': ['the'] A dictionary! }

  49. Model creation: 1) start with the prevwd as '$' 2) for each nextwdin the list of words, add it in ... 3) then change nextwdto prevwd or '$'... if nextwd [-1] is punctuation.

  50. hw8pr2… $ : [ I, I ] I : [ like, eat ] like : [ spam ] eat : [ poptarts ] pw nw I like spam. I eat poptarts! d = {} pw = for nw in LoW: if pwnot in d: d[pw] = else: d[pw] +=

More Related