IST 338 today ! A whole new class of programming CS building - - PowerPoint PPT Presentation

ist 338 today
SMART_READER_LITE
LIVE PREVIEW

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:


slide-1
SLIDE 1

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

slide-2
SLIDE 2

Not an end, but a beginning

Final projects

Foziah: website using Django (or Flask)

www.cs.hmc.edu/twiki/bin/view/CS5/IST338ProjectsPage2015

slide-3
SLIDE 3
  • also: www.cs.hmc.edu/~jgrasel/

Mandelbrot Set!

  • ex. cr. grading…
slide-4
SLIDE 4

Classes and Objects

slide-5
SLIDE 5

Everything in Python is an object! Its capabilities depend on its class.

type functions what's more, you can build your own... "methods"

slide-6
SLIDE 6

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 str constructor. Shows the type of s is str Shows all of the methods (functions) of s Let's try some!

slide-7
SLIDE 7

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 (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

slide-8
SLIDE 8

A Date object, d

memory location ~ 42042778 day month year

d

4

2015

8

slide-9
SLIDE 9

A Date object, d

memory location ~ 42042778 day month year

d

4

2015

8

It's an alien date!

slide-10
SLIDE 10

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

The Date class

what?!

slide-11
SLIDE 11

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

The Date class

This is the constructor for Date objects As is typical, it assigns input data to the data members. This is the start of a new type called Date It begins with the keyword class These are data members – they are the information inside every Date object.

slide-12
SLIDE 12

>>> d = Date(4,8,2015) >>> d.month 4 >>> d.day 6

Date

d contains data members named day, month, and year

>>> d 04/08/2015

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

>>> d.isLeapYear() False

The isLeapYear method returns True or False. How does it know what year to check?

The repr!

slide-13
SLIDE 13

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

The Date class

  • This is the repr for Date objects

It tells Python how to print these objects. Why self instead of d ?

slide-14
SLIDE 14

>>> d = Date(4,8,2015) >>> d 04/08/2015

self

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

slide-15
SLIDE 15

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? """

The Date class

  • which are leap years?
slide-16
SLIDE 16

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

slide-17
SLIDE 17

Special Dates?

slide-18
SLIDE 18
slide-19
SLIDE 19
slide-20
SLIDE 20

Emily M

slide-21
SLIDE 21

==

  • vs. equals

>>> d = Date(11,12,2013) >>> d 11/12/2013 >>> d2 = Date(11,12,2013) >>> d2 11/12/2013

this constructs a different Date

What id is on your Date?

>>> d == d2 False

UFO license Area 51, CA

How can this be False ?

slide-22
SLIDE 22

Two Date objects:

memory location ~ 42042778 day month year

d

11

2013

12

  • riginals underneath…

== compares memory locations, not contents

slide-23
SLIDE 23

>>> d = Date(11,12,2013) >>> d 11/12/2013 >>> d2 = Date(11,12,2013) >>> d2 11/12/2013

What date is on your id? What id is on your Date?

>>> d.equals(d2) True

UFO license Area 51, CA

this constructs a different Date

== vs. equals

slide-24
SLIDE 24

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

equals

  • self
slide-25
SLIDE 25

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

isBefore

slide-26
SLIDE 26

class Date: def isBefore(self, d2): """ if self is before d2, this should return True; else False """ if [self.year,self.month,self.day] < [ d2.year, d2.month, d2.day] return True else: return False

I want even LESS !

isBefore

slide-27
SLIDE 27

Date's purpose…?!

>>> d = Date(5,14,2015) >>> d 05/14/2015

always create with the CONSTRUCTOR …

>>> d.tomorrow() >>> d 05/15/2015 >>> d.subNDays(37)

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!

slide-28
SLIDE 28

Add these to your Date class!

no computer required…

  • Prof. Benjamin !

Lab today – or tomorrow

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…

slide-29
SLIDE 29

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 > ____________:

Quiz

Don't return anything. This CHANGES the date

  • bject that calls it.

DIM looks pretty bright to me! first, add 1 to self.day then, adjust the month and year, but

  • nly if needed

Extra: how could you make this work for leap years, too?

Implement tomorrow !

Name(s) _____________________________

slide-30
SLIDE 30

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]

Quiz

Don't return anything. This CHANGES the date

  • bject that calls it.

DIM looks pretty bright to me! first, add 1 to self.day then, adjust the month and year,

  • nly if needed

Extra: how could you make this work for leap years, too?

Implement tomorrow !

Name(s) _____________________________

slide-31
SLIDE 31

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!

slide-32
SLIDE 32

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

slide-33
SLIDE 33

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

slide-34
SLIDE 34

Not all years are the same!

slide-35
SLIDE 35

Using classes + objects

files dictionaries

hw10pr3

If I had a dictionary, I guess I could look up what it was!

hw10pr2

Connect Four Board class file and dictionary classes

Building classes... ... vs. using the library

slide-36
SLIDE 36

Classes: DIY data

Class: a user-defined datatype Object: data or a variable whose type is a class Method: a function defined in a class called by an object Constructor: the __init__ function for creating a new object

d = Date( 4, 8, 2015 ) d.tomorrow() print d

repr: the __repr__ function returning a string to print self: in a class, the name of the object calling a method

constructor

  • bject

method uses repr d would be named self inside the Date class...

design-it-yourself!

data member: the data in self: self.day, self.month, self.year

slide-37
SLIDE 37

Why classes?

Python has no Connect-four datatype… | | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O|

  • 0 1 2 3 4 5 6

Care for a game?

… but now we can fix that!

slide-38
SLIDE 38

Data design…

(Data Members) What data do we need? (Methods) What are capabilities we want?

slide-39
SLIDE 39

Our Board object, b

Board b

width str str str str str str str str str data str str str height

How could we set ? and ? to 'X'

str str str str str str str str str str str str

6 5

rows str str str str str str columns

?

b.

?

slide-40
SLIDE 40

__init__

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.

slide-41
SLIDE 41

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

__repr__

| | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O|

  • 0 1 2 3 4 5 6
slide-42
SLIDE 42

| | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O|

  • 0 1 2 3 4 5 6

Quiz

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) Run b.addMove(3,'O')

1 2 3 4 5 1 2 3 4 5 6

(2) Bugs! Can you fix them?! b Name(s) ___________________________

slide-43
SLIDE 43

| | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O|

  • 0 1 2 3 4 5 6

Quiz

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) Run b.addMove(3,'O')

1 2 3 4 5 1 2 3 4 5 6

(2) Bugs! Can you fix them?! b Try this on the back page first…

slide-44
SLIDE 44

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 #

Let's finish this allowsMove method …

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|

  • 0 1 2 3 4 5 6

1 2 3 4 5 1 2 3 4 5 6

b

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

slide-45
SLIDE 45

hw10pr2: Board class

__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

  • utputs a string

checks if any space is left checks if a player has won

hostGame( self )

the game...

delMove( self, col )

removes a checker

Which are similar to others? Which requires the most thought?

to write... to write... to write... to write...

slide-46
SLIDE 46

winsFor( self, ox )

X O

b

b.winsFor('X')

  • r 'O'

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(

slide-47
SLIDE 47

Why objects and classes?

Elegance: Objects hide complexity!

if b.winsFor( 'X' ) == True: if d.isBefore( d2 ) == True:

Simple – and INVITING -- building blocks!

slide-48
SLIDE 48

CS 5 this week

files dictionaries

hw10pr3

If I had a dictionary, I guess I could look up what it was!

hw10pr2

Connect Four Board class file and dictionary classes

Building classes... ... vs. using the library

Hw #10 due 4/12

slide-49
SLIDE 49

Files

>>> 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', ... ]

In Python reading files is no problem…

  • pens the file and calls it f

reads the whole file into the string text text.split() returns a list of each "word" closes the file (optional)

slide-50
SLIDE 50

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.

slide-51
SLIDE 51

Dictionaries

A dictionary is a set of key - value pairs >>> d = {} >>> d[1996] = 'rat' >>> d[1995] = 'pig' >>> d {1995:'pig', 1996:'rat'} >>> d[1995] 'pig'

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!

key value

slide-52
SLIDE 52

More on dictionaries

Strings can be keys, too!

>>> 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

  • f all key, value pairs

keys can be anything handled by value, not reference!

slide-53
SLIDE 53

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.

Counting distinct words with a dictionary…

slide-54
SLIDE 54

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

  • ccurences of each word

with a dictionary, d. file handling word counting

most/least common?

slide-55
SLIDE 55

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… Who? What word?

successful unsuccessful

http://www.pathguy.com/shakeswo.htm http://www.shakespeare-online.com/biography/wordsinvented.html

gust besmirch unreal superscript watchdog swagger affined rooky attasked

  • ut-villianed
slide-56
SLIDE 56

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

successful unsuccessful

http://www.pathguy.com/shakeswo.htm http://www.shakespeare-online.com/biography/wordsinvented.html

gust besmirch unreal superscript watchdog swagger affined rooky attasked

  • ut-villianed
  • J. K. Rowling
slide-57
SLIDE 57

Algorithmic authoring?

slide-58
SLIDE 58

Markov Models

Techniques for modeling any sequence of natural data Each item depends only on the one immediately before it .

1st-order Markov Model (defining property)

speech, text, sensor data...

slide-59
SLIDE 59

Our Markov Model

Markov Model: Original file: { '$': ['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'] }

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?

slide-60
SLIDE 60

I like poptarts and 42 and spam. Will I get spam and poptarts for the holidays? I like spam poptarts! { '$': ['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'] }

Our Markov Model

Markov Model: Original file:

is a dictionary!

slide-61
SLIDE 61

Model creation: 1) start with the prevwd as '$' 2) for each nextwd in the list of words, add it in ... 3) then change nextwd to prevwd or '$'...

if nextwd [-1] is punctuation.

d = {} d['I'] = . d['I'] += . d['like'] = . d['$'] = ['I']

slide-62
SLIDE 62

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?

I like spam. I eat poptarts!

pw nw

$ : [ I, I ] I : [ like, eat ] like : [ spam ] eat : [ poptarts ]

Model creation in Python

goal for d

slide-63
SLIDE 63

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

  • f words following prevwd.

Model creation

reset variables appropriately here – be sure not to forget to check if the sentence has ended!

slide-64
SLIDE 64

Markov Models are generative!

Generated text:

A key benefit of Markov Models is that they can generate feasible data!

I get spam poptarts! I like poptarts and 42 and spam. I like spam and 42 and 42 and 42 and spam. Will I like poptarts and 42 and poptarts and 42 and poptarts and 42 and 42 and poptarts and spam. I get spam and 42 and 42 and... Original file: I like poptarts and 42 and spam. Will I get spam and poptarts for the holidays? I like spam poptarts!

I agree!

slide-65
SLIDE 65

Generating text: 1) start with prevwd as the '$' string 2) choose a nextwd that follows prevwd, at random. 3) print nextwd 4) nextwd or '$' becomes prevwd Model creation: 1) start with the prevwd as '$' 2) for each nextwd in the list of words, add it in ... 3) then change nextwd to prevwd or '$'...

if nextwd [-1] was punctuation. if nextwd [-1] was punctuation.

demo…

slide-66
SLIDE 66

WMSCI

slide-67
SLIDE 67

WMSCI 2005

Markov-generated submission accepted to WMSCI 2005

http://pdos.csail.mit.edu/scigen/

slide-68
SLIDE 68

theirs was more than a first-order model…

slide-69
SLIDE 69

presentation…

in costume!

slide-70
SLIDE 70

Thesis worries?

Have a worry-free weekend!

Other papers due?