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.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University
Dictionaries: Keeping track of pairs
Annoucements  Next labs 9 and 10 are paired for everyone. So don’t miss the lab.  There is a review session for the quiz on Monday, November 4, at 8:00.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Substitute FAQs SubFinder Overview. FAQs Do I have to have touch-tone service to use SubFinder? No, but you do need a telephone that can be switched from.
Lists Introduction to Computing Science and Programming I.
HW 1: Problems 3 & 4 EC 1 & 2.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Main task -write me a program
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
An Introduction to Textual Programming
Abstraction IS 101Y/CMSC 101 Computational Thinking and Design Tuesday, September 17, 2013 Carolyn Seaman University of Maryland, Baltimore County.
Lists in Python.
A whole new class of programming CS 5 today HW10: Due Sun, Nov 15 Pr0: Ariane 5 Reading Pr1/Lab:the Date class Pr2 Connect4Board Pr3 Connect4Player (extra.
The not-so-subtle art of singling out the best (and worst) of anything… Computing with language Computing to the max You know this would make me hungry…
CS 5 Today Today: Midterm Exam #2 M/T 11/16-17/09, in class Life in 3d? filesdictionaries David Miller ! but there is an optional, ex. cr. circuit-building.
IS 313 Today Schedule Week 0: Classes Objects You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where.
Welcome to my conference! February th grade Guadalupe.
Def tomorrow(self): """Changes the calling object so that it represents one calendar day after the date it originally represented. """ if self.month in.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
If statements while loop for loop
Welcome to CS 115! Introduction to Programming. Class URL Write this down!
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Welcome to CS61A Disc. 29/47 :D Dickson Tsai OH: Tu, Th 4-5pm 411 Soda Previous stop: None >>> Today: Working effectively in.
Google App Engine MemCache ae-09-session
Lists, Tuples, Dictionaries, … + lots of computer work for the programmer's work! T = {'abe' :['homer','herb'], 'jackie':['marge','patty','selma'], 'homer'
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Chapter 5 Files and Exceptions I. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What is a file? A.
Software Development. Software Development Loop Design  Programmers need a solid foundation before they start coding anything  Understand the task.
Ionut Trestian Northwestern University
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
EECS 110: Lec 13: Dictionaries Aleksandar Kuzmanovic Northwestern University
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
Reading 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.
EECS 110: Lec 14: Classes and Objects
EECS 110: Lec 15: Classes and Objects (2)
CS this week 4 Building classes vs. using the library hw10pr2
EECS 110: Lec 13: Dictionaries
EECS 110: Lec 12: Mutable Data
EECS 110: Lec 17: Review for the Final Exam
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Introduction to Object-Oriented Programming (OOP)
Markov Model a language processing model
Files and Dictionaries
Files and Dictionaries
CS190/295 Programming in Python for Life Sciences: Lecture 6
Ionut Trestian Northwestern University
Introduction to Object-Oriented Programming (OOP)

EECS 110: Lec 14: Classes and Objects
CS this week 4 Building classes vs. using the library hw10pr2
Northwestern University
Arrays.
EECS 110: Lec 12: Mutable Data
Introduction to Object-Oriented Programming (OOP)
Files and Dictionaries
Lecture 6 - Recursion.
Presentation transcript:

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

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

Tomorrow's HW Problem #1: Wandering 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

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!

Thanks to Alex Hagen !

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…

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

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?

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 !

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

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 !

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. 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' )

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

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

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

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'

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'

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…

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

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

A family dictionary?

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 Tree.has_key( person ): Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Who is favored ? Side effects ?

A functional family? def addChild( person, Tree, jr ): """ adds person's new child to Tree """ For example, >>> addChild( 'lisa', T, 'abejr' )

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

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…

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

Name that author… ?

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

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

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:

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?

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

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.

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

Creating a Markov Model def createDictionary( fileName ):

Generating Markov text def generateText( d, n ): d is the dictionary, and n is the number of words to generate…

Number of distinct words? Shakespeare used 31,534 different words and a grand total of 884,647 words counting repetitions (across his works) Many coinages: Shakespeare J. K. Rowling Active vocabulary estimates range from 10,000-60,000. Passive vocabulary estimates are much higher.

WMSCI

WMSCI 2005 Randomly-generated submission accepted to WMSCI No end to the WMSCI s…

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

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.

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.

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

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

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

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

Examples… Do reference libraries have library references? Python's class libraries… Graphics libraries >>> f = urllib.urlopen( ' ) >>> text = f.read() >>> text[:50]

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

But Why ? Flexibility Reusability Abstraction ordinary data structures create-your-own write once, take anywhere worry once, use anywhere

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

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.

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

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

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?

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!

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 )

Double Date >>> d2 = d >>> d 11/26/2007 >>> d.yesterday() >>> >>> d2 >>> d2 == d >>> d2.equals(d) Excuse me -- id s please! What happens here?

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?

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?

"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/ /27/2007 how might you fix this problem?

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/ /27/2007

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]

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…

Unusual calendar years…

Lab … and hw questions