A whole new class of programming
IST 338 today!
CS: theory + practice CS building blocks: functions and composition
- behind the CS
curtain: circuits, assembly, loops Designing Data!
The Date class
IST 338 today ! A whole new class of programming CS building - - PowerPoint PPT Presentation
IST 338 today ! A whole new class of programming CS building blocks: functions and composition behind the CS curtain : circuits, assembly, loops The Designing Date class Data! CS:
The Date class
Not an end, but a beginning
www.cs.hmc.edu/twiki/bin/view/CS5/IST338ProjectsPage2015
Take strings, for example:
['__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 str constructor. Shows the type of s is str Shows all of the methods (functions) of s Let's try some!
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 (4) Python signals special methods with two underscores:
I guess we should doubly underscore these two methods!
__init__ is called the constructor; it creates new objects __repr__ tells Python how to print its objects (3) In its methods, objects refer to themselves as self
It's an alien date!
class Date: """ 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
class Date: """ 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
d contains data members named day, month, and year
This is a class. It is a user-defined datatype that you'll build in Lab 10 this week…
Constructor!
the representation of an object of type Date
The isLeapYear method returns True or False. How does it know what year to check?
The repr!
class Date: """ 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
class Date: """ 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 def isLeapYear( self ): """ anyone know the rule? """
class Date: def __init__( self, mo, dy, yr ): (constructor) def __repr__(self): (for printing) def isLeapYear( 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
Emily M
this constructs a different Date
What id is on your Date?
UFO license Area 51, CA
How can this be False ?
What date is on your id? What id is on your Date?
UFO license Area 51, CA
this constructs a different Date
class Date: def __init__( self, mo, dy, yr ): def __repr__(self): def isLeapYear(self): def equals(self, d2): """ returns True if they represent the same date; False otherwise """ if return True else: return False
class Date: def isBefore(self, d2): """ if self is before d2, this should return True; else False """ if self.year < d2.year: return True if self.year > d2.year: return False # here, the years are EQUAL! if self.month < d2.month: return True if self.month > d2.month: return False # here, the years and months are EQUAL! if self.day < d2.day: return True return False
>>> d = Date(1,1,2016) >>> d2 = Date(4,6,2015) >>> d.isBefore( d2 ) False
I want even LESS !
always create with the CONSTRUCTOR …
lots of printing, but no return value!
the tomorrow method returns nothing at all. Is it doing anything? Why is this important? Some methods return a value; others change the object that call it! d has changed!
Add these to your Date class!
no computer required…
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…
class Date: def tomorrow(self): """ moves the date ahead 1 day """ DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31] self.day _________ if self.day > ____________:
Don't return anything. This CHANGES the date
DIM looks pretty bright to me! first, add 1 to self.day then, adjust the month and year, but
Extra: how could you make this work for leap years, too?
Implement tomorrow !
Name(s) _____________________________
class Date: def tomorrow(self): """ moves the date ahead 1 day """ DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31]
Don't return anything. This CHANGES the date
DIM looks pretty bright to me! first, add 1 to self.day then, adjust the month and year,
Extra: how could you make this work for leap years, too?
Implement tomorrow !
Name(s) _____________________________
class Date: def tomorrow(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! if self.day > DIM[self.month]: # check day self.month += 1 self.day = 1 if self.month > 12: # check month self.year += 1 self.month = 1
better as a variable!
class Date: def tomorrow(self): """ moves the date ahead 1 day """ if self.isLeapYear() == True: fdays = 29 else: fdays = 28 DIM = [0,31,fdays,31,30,31,30,31,31,30,31,30,31] self.day += 1 # add 1 to the day! if self.day > DIM[self.month]: # check day self.month += 1 self.day = 1 if self.month > 12: # check month self.year += 1 self.month = 1
class Date: def tomorrow(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 # add 1 to the day! if self.day > DIM[self.month]: # check day self.month += 1 self.day = 1 if self.month > 12: # check month self.year += 1 self.month = 1
files dictionaries
If I had a dictionary, I guess I could look up what it was!
Connect Four Board class file and dictionary classes
constructor
method uses repr d would be named self inside the Date class...
design-it-yourself!
Care for a game?
Board b
width str str str str str str str str str data str str str height
str str str str str str str str str str str str
rows str str str str str str columns
?
?
class Board: """ a datatype representing a C4 board with an arbitrary number of rows and cols """ def __init__( self, width, height ): """ the constructor for objects of type Board """ self.width = width self.height = height W = self.width H = self.height self.data = [ [' ']*W for row in range(H) ] This list comprehension lets us create H independent rows with W independent columns each.
def __repr__(self): """ this method returns a string representation for an object of type Board """ H = self.height W = self.width s = '' for r in range( H ): s += '|' for c in range( W ): s += self.data[r][c] + '|' s += '\n' s += (2*W+1)*'-' # what will you need to add right here? return s
| | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O|
| | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O|
class Board: def addMove(self, col, ox): """ buggy version! """ H = self.height for row in range(0,H): if self.data[row][col] != ' ': self.data[row-1][col] = ox self.data[H][col] = ox
a C4 board col # 'X' or 'O'
1 2 3 4 5 1 2 3 4 5 6
| | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O|
class Board: def addMove(self, col, ox): """ buggy version! """ H = self.height for row in range(0,H): if self.data[row][col] != ' ': self.data[row-1][col] = ox self.data[H][col] = ox
a C4 board col # 'X' or 'O'
1 2 3 4 5 1 2 3 4 5 6
class Board: def allowsMove(self, col): """ True if col is in-bounds + open False otherwise """ H = self.height W = self.width D = self.data if
a C4 board col #
If it's in-bounds and not full, return True. If col is out-of-bounds or full, return False.
| | |X|O| | |O| | | |X|X| | |X| | | |O|O| | |O| | | |O|X| | |O| | |X|X|X| |O|X| |X|O|O|O|X|X|O|
1 2 3 4 5 1 2 3 4 5 6
b.allowsMove(0) == True b.allowsMove(1) == True b.allowsMove(2) == False b.allowsMove(3) == False b.allowsMove(4) == True b.allowsMove(5) == True b.allowsMove(6) == False b.allowsMove(7) == False
__init__( self, width, height ) allowsMove( self, col ) __repr__( self ) addMove( self, col, ox ) isFull( self ) winsFor( self, ox )
the “constructor” checks if allowed places a checker
checks if any space is left checks if a player has won
hostGame( self )
the game...
delMove( self, col )
removes a checker
to write... to write... to write... to write...
Watch out for corner cases!
def winsFor(self, ox): """ does ox win? """ H = self.height W = self.width D = self.data for row in range( for col in range(
Simple – and INVITING -- building blocks!
files dictionaries
If I had a dictionary, I guess I could look up what it was!
Connect Four Board class file and dictionary classes
Hw #10 due 4/12
In Python reading files is no problem…
reads the whole file into the string text text.split() returns a list of each "word" closes the file (optional)
def word_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 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.
This seems like the key to dictionaries' value…
creates an empty dictionary, d 1996 is the key 'rat' is the value 1995 is the key 'pig' is the value Curly! And colony!
>>> d = {'pig': 1995, 'rat': 1996} >>> 'pig' in d >>> 'cat' in d True False >>> len(d) 2 >>> d.keys() [ 'pig', 'rat' ] >>> d.values() [ 1996, 1995 ] >>> d.items() [ ('rat', 1996), ('pig', 1995) ]
Diciontaries don't seem moronic to me!
in checks if a key is present d.keys() returns a list of all keys len () returns the # of keys d.values () returns a list of all values
d.items () returns a list
keys can be anything handled by value, not reference!
WOULD YOU LIKE THEM IN A HOUSE? WOULD YOU LIKE THEN WITH A MOUSE? I DO NOT LIKE THEM IN A HOUSE. I DO NOT LIKE THEM WITH A MOUSE. I DO NOT LIKE THEM HERE OR THERE. I DO NOT LIKE THEM ANYWHERE. I DO NOT LIKE GREEN EGGS AND HAM. I DO NOT LIKE THEM, SAM-I-AM.
def vocab_count( filename ): """ vocabulary-counting program """ f = open( filename ) text = f.read() f.close() LoW = text.split() print "There are", len(LoW), "words." d = {} for wd in LoW: if wd not in d: d[wd] = 1 else: d[wd] += 1 print "There are", len(d), "distinct words.\n" return d # return d for later use by other code…
Tracking the number of
with a dictionary, d. file handling word counting
most/least common?
http://www-math.cudenver.edu/~wbriggs/qr/shakespeare.html
successful unsuccessful
http://www.pathguy.com/shakeswo.htm http://www.shakespeare-online.com/biography/wordsinvented.html
http://www-math.cudenver.edu/~wbriggs/qr/shakespeare.html
successful unsuccessful
http://www.pathguy.com/shakeswo.htm http://www.shakespeare-online.com/biography/wordsinvented.html
1st-order Markov Model (defining property)
speech, text, sensor data...
is a dictionary! What are the missing values? What are the keys? What are the values? What is the '$'? Why do some keys seem missing?
is a dictionary!
if nextwd [-1] is punctuation.
d = {} pw = for nw in LoW: if pw not in d: d[pw] = else: d[pw] += # what variables need to change here? how do they?
goal for d
def createDictionary( filename ): """ creates a 1st-order M.Model """ f = open( filename ) text = f.read() f.close() LoW = text.split() d = {} prevwd = '$' for nextwd in LoW: if prevwd not in d: d[prevwd] = else: d[prevwd] += return d
We want the KEY to be prevwd. We want the VALUE to be the list
reset variables appropriately here – be sure not to forget to check if the sentence has ended!
A key benefit of Markov Models is that they can generate feasible data!
I agree!
if nextwd [-1] was punctuation. if nextwd [-1] was punctuation.
http://pdos.csail.mit.edu/scigen/