EECS 110: Lec 13: Dictionaries

Slides:



Advertisements
Similar presentations
Course A201: Introduction to Programming 10/28/2010.
Advertisements

Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University
Dictionaries: Keeping track of pairs
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
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.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
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.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
Built-in Data Structures in Python An Introduction.
Lists CS303E: Elements of Computers and Programming.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
GE3M25: Computer Programming for Biologists Python, Class 5
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Ionut Trestian Northwestern University
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
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.
EECS 110: Lec 13: Dictionaries Aleksandar Kuzmanovic Northwestern University
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
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.
Next Week… Quiz 2 next week: –All Python –Up to this Friday’s lecture: Expressions Console I/O Conditionals while Loops Assignment 2 (due Feb. 12) topics:
EECS 110: Lec 14: Classes and Objects
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 21, 2016.
CS this week 4 Building classes vs. using the library hw10pr2
EECS 110: Lec 12: Mutable Data
EECS 110: Lec 17: Review for the Final Exam
Algorithmic complexity: Speed of algorithms
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
CS-104 Final Exam Review Victor Norman.
Markov Model a language processing model
Files and Dictionaries
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Computer Science 2 Hashing
Bryan Burlingame Halloween 2018
Files and Dictionaries
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Lesson 09: Lists Topic: Introduction to Programming, Zybook Ch 8, P4E Ch 8. Slides on website.
6. Lists Let's Learn Python and Pygame
4. sequence data type Rocky K. C. Chang 16 September 2018
Ionut Trestian Northwestern University
String and Lists Dr. José M. Reyes Álamo.
EECS 110: Lec 14: Classes and Objects
Chapter 5: Lists and Dictionaries
Lesson 09: Lists Class Chat: Attendance: Participation
Algorithmic complexity: Speed of algorithms
Lists Part 1 Taken from notes by Dr. Neil Moore
CS this week 4 Building classes vs. using the library hw10pr2
Files Handling In today’s lesson we will look at:
Computer Science 2 Hashing.
Northwestern University
How to use hash tables to solve olympiad problems
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Algorithmic complexity: Speed of algorithms
Bryan Burlingame Halloween 2018
Python Review
EECS 110: Lec 12: Mutable Data
Files and Dictionaries
Presentation transcript:

EECS 110: Lec 13: Dictionaries Aleksandar Kuzmanovic Northwestern University http://networks.cs.northwestern.edu/EECS110-s17/

EECS 110 Today Today: Hw 5 Next week: Python's objects & Classes Due this Sunday files dictionaries Next week: Python's objects & Classes

+= mutates Mutable Data (lists) WARNING: For mutable data types, the following are NOT the same MUTATES A (B changes too) A = [] B = A A += [42, 42] NOT THE SAME! A = [] B = A A = A + [42, 42] COPIES A (B does not change)

More Practice with Mutation What are the values of A, B, C and D at the indicated points? def mystery1(L1, N, C): for i in L1: if i == N: C += 1 return C def mystery2(C): for i in range(len(C)): C[i] *= 2 >>> A = [22, 10, 30] >>> B = 22 >>> C = 0 >>> D = mystery1(A, B, C) >>> mystery2(A) 1) 2) 1 2

More Practice with Mutation What are the values of A, B, C and D at the indicated points? def mystery1(L1, N, C): for i in L1: if i == N: C += 1 return C def mystery2(C): for i in range(len(C)): C[i] *= 2 >>> A = [22, 10, 30] >>> B = 22 >>> C = 0 >>> D = mystery1(A, B, C) >>> mystery2(A) >>> A 1) 2) A = [22, 10, 30] B = 22 C = 0 D = 1 1 2

More Practice with Mutation What are the values of A, B, C and D at the indicated points? def mystery1(L1, N, C): for i in L1: if i == N: C += 1 return C def mystery2(C): for i in range(len(C)): C[i] *= 2 >>> A = [22, 10, 30] >>> B = 22 >>> C = 0 >>> D = mystery1(A, B, C) >>> mystery2(A) >>> A 1) 2) A = [22, 10, 30] B = 22 C = 0 D = 1 A = [44, 20, 60] 1 2

Name that author… ?

HW5 Pr 2: Read some text and automatically generate new (reasonable HW5 Pr 2: Read some text and automatically generate new (reasonable?) text

No end to the WMSCI emails… Randomly-generated submission accepted to WMSCI http://pdos.csail.mit.edu/scigen/ No end to the WMSCI emails…

Markov Model I like spam. I like toast and spam. The text file: Technique for modeling any sequence of natural data 1st-order Markov Model Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: For each word, keep track of the words that can follow it (and how often) The Model: I: like, like, eat like: spam, toast spam.: $ $: I, I, I toast: and eat: ben and: spam, jerry's ben: and jerry's: ice ice: cream cream: too. too.: $ We can repeat words to indicate frequency $ indicates beginning of a sentence

I like spam. I like spam. I like toast and jerry's ice cream too. 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.

HW5 Pr 2: Need to be able to… Read text from a file Compute and store the model Generate the new text

Reading Files In Python reading files is no problem… >>> f = open( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close()

Files In Python reading files is no problem… >>> f = open( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() opens the file and calls it f reads the whole file and calls it text text is a single string containing all the text in the file But how to process the text from here…? closes the file (closing Python does the same)

String Manupulation >>> text 'This is a file.\nLine 2\nLast line!\n' >>> print(text) This is a file. Line 2 Last line! >>> text.split() ['This', 'is', 'a', 'file.', 'Line', '2', 'Last', 'line!'] >>> lines = text.split('\n') >>> lines ['This is a file.', 'Line 2', 'Last line!', ''] Returns a list of the words in the string (splitting at spaces, tabs and newlines) Returns a list of the lines in the string (splitting at newlines)

Objects, objects, everywhere! >>> L = [] # create a list, L >>> dir(L) # see all of L's methods all list methods appear -- lots of them including append, index, remove, and sort >>> help(L.sort) # I wonder… index: integer – return first index of value >>> help(L.index) # What does this do?

but there's a fundamental difference… what and why? List methods String methods >>> dir([]) >>> dir('') capitalize center count find index isalpha lower replace split strip title upper and ~10 more… append count extend index insert pop remove reverse sort help can help but there's a fundamental difference… what and why?

Mutable vs. immutable objects Strings are immutable objects. Lists are mutable objects. (So are numbers.) >>> s = 'string' >>> s.replace('st','') 'ring' >>> s 'string' >>> L = [2,1,3] >>> L.sort() >>> L [1,2,3] no return value returns a NEW string L has changed. s has NOT changed

HW5 Pr 2: Need to be able to… Read text from a file Compute and store the model Generate the new text

Lists vs. Dictionaries Lists are not perfect… L reference 5 42 L[0]

Lists vs. Dictionaries Lists are not perfect… reference 5 42 You can't choose what to name data. L L[0] L[1] L[0], L[1], …

Lists vs. Dictionaries Lists are not perfect… reference 5 42 You can't choose what to name data. L L[0] L[1] L[0], L[1], … You have to start at 0. L[1988] = 'dragon' L[1989] = 'snake'

Lists vs. Dictionaries Lists are not perfect… reference 5 42 You can't choose what to name data. L L[0] L[1] L[0], L[1], … You have to start at 0. L[1988] = 'dragon' L[1989] = 'snake' Some operations can be slow for big lists … if 'dragon' in L:

Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error It's a list where the index can be any immutable-type key.

Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error creates an empty dictionary, d 1988 is the key 'dragon' is the value 1989 is the key 'snake' is the value Anyone seen this before? Retrieve data as with lists… or almost ! It's a list where the index can be any immutable-type key.

delete a key (and its value) More on dictionaries Dictionaries have lots of built-in methods: >>> d = {1988: 'dragon', 1989: 'snake'} >>> d.keys() [ 1989, 1988 ] >>> 1988 in d True >>> 1969 in d False >>> d.pop( 1988 ) 'dragon' get all keys check if a key is present delete a key (and its value)

A family dictionary?

A family dictionary… T['abe'] 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 family dictionary… T['abe'] 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'] ['homer','herb'] How to get 'selma' from T?

A family dictionary… T['abe'] 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'] ['homer','herb'] How to get 'selma' from T? T['jackie'][2] (T['jackie'] is a list)

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 person in Tree: 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 ): For example, >>> addChild( 'lisa', T, 'abejr' ) def addChild( person, Tree, jr ): """ adds person's new child to Tree ""“

A functional family? def addChild( person, Tree, jr ): For example, >>> addChild( 'lisa', T, 'abejr' ) def addChild( person, Tree, jr ): """ adds person's new child to Tree ""“ if person in Tree: kids = Tree[person] kids += [jr]

A challenge… prov = { 'BC': 0, 'AB': 0, … } def provinceChallenge( prov ): """ prov is a dictionary of Canada's provinces -- the challenge is to name them all! """ while 0 in prov.values(): guess = input("Name a province: ") if guess not in prov: print 'Try again...' elif prov[guess] == 0: print 'Yes!' prov[guess] += 1 else: print('Already guessed...’) print('Phew!’) help?!

“Quiz” def favChild( person, Tree ): if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Change this code so that it keeps track of how many times you've guessed each item. 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 provinceChallenge( prov ): while 0 in prov.values(): guess = input("Guess: ") if guess not in prov: print('Try again...’) elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed...') def favGChild( person, Tree ):

def provinceChallenge( prov ): while 0 in prov.values(): Change this code so that it tells you how many times you've guessed the same province… first, for real provinces then, for incorrect guesses… def provinceChallenge( prov ): while 0 in prov.values(): guess = input("Guess: ") if guess not in prov: print('Try again... ’) elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed...‘)

def provinceChallenge( prov ): prov['incorrect']=0 Change this code so that it tells you how many times you've guessed the same province… first, for real provinces then, for incorrect guesses… def provinceChallenge( prov ): prov['incorrect']=0 while 0 in prov.values(): guess = input("Guess: ") if guess not in prov: print('Try again... ’) prov['incorrect'] += 1 elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed...‘)

def favChild( person, Tree ): if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none.

def favGChild( person, Tree ): gChildren = [] if person in Tree : def favChild( person, Tree ): if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none. def favGChild( person, Tree ): gChildren = [] if person in Tree : for child in Tree[person]: if child in Tree: gChildren += Tree[child] if gChildren == []: return 'no one' else: gChildren.sort() return gChildren[0]

Markov Model I like spam. I like toast and spam. The text file: Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : ['like', 'like', 'eat'], '$' : ['I', 'I', 'I'], The Model: