CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012.

Slides:



Advertisements
Similar presentations
CS61A Lecture 25 Delayed Sequences Jom Magrotker UC Berkeley EECS July 31, 2012.
Advertisements

Announcements You survived midterm 2! No Class / No Office hours Friday.
CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.
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.
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.
S UCCESSFUL T EXTBOOK R EADING AND N OTE T AKING OR How to get the most from your text without going crazy!
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Lists Introduction to Computing Science and Programming I.
1 Introduction to Computability Theory Lecture12: Reductions Prof. Amos Israeli.
CSC1016 Coursework Clarification Derek Mortimer March 2010.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
CS503: Tenth Lecture, Fall 2008 Review Michael Barnathan.
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Today’s quiz on 8.2 B Graphing Worksheet 2 will be given at the end of class. You will have 12 minutes to complete this quiz, which will consist of one.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Please open Daily Quiz 34. A scientific calculator may be used on this quiz. You can keep your yellow formula sheets out when you take the quiz. Remember.
Python Data Structures
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
CS61A Lecture 6 Recursion Tom Magrino and Jon Kotker UC Berkeley EECS June 26, 2012.
UW CSE 190p Section 8/2, Summer 2012 Dun-Yu Hsiao.
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
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.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Lecture 131 CS110 Lecture 13 Thursday, March 11, 2004 Announcements –hw5 due tonight –Spring break next week –hw6 due two weeks from tonight Agenda –questions.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Computing Science 1P Lecture 14: Friday 2 nd February Simon Gay Department of Computing Science University of Glasgow 2006/07.
CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012.
1 CS1100 Fall Instructor: David Gries CS100M: Matlab No prior programming experience One semester of calculus Math & engineering type problems CS100J:
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
Lecture 04 – Models of memory Mutable and immutable data.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
1 CS 101 Today’s class will begin about 5 minutes late We will discuss the lab scheduling problems once class starts.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
Lecture on Set! And Local CS 2135 Copyright Kathi Fisler, 2002 This material requires Advanced Language Level.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
Written by: Dr. JJ Shepherd
CIT 590 Intro to Programming Lecture 4. How are assignments evaluated Pay attention to what the HW says it is trying to teach you about ‘modular programming’
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
CS61A Lecture 10 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 3, 2012.
CS61A Lecture 11 Immutable Trees Jom Magrotker UC Berkeley EECS July 5, 2012.
CS61A Lecture 1 Introduction and Basics Tom Magrino and Jon Kotker UC Berkeley EECS June 18, 2012.
Today’s Agenda ML Development Workflow –Emacs –Using use –The REPL More ML –Shadowing Variables –Debugging Tips –Boolean Operations –Comparison Operations.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
1 Computer Science 1021 Programming in Java Geoff Draper University of Utah.
CMSC201 Computer Science I for Majors Lecture 23 – Algorithms and Analysis Prof. Katherine Gibson Based on slides from previous iterations.
CMSC201 Computer Science I for Majors Lecture 22 – Searching
CS190/295 Programming in Python for Life Sciences: Lecture 6
Java Programming Loops
Java Programming Loops
Midterm Review October 23, 2006 ComS 207: Programming I (in Java)
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Computer Science
Presentation transcript:

CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012

2 C OMPUTER S CIENCE IN THE N EWS (T WO Y EARS A GO )

3 C OMPUTER S CIENCE IN THE N EWS

4 T ODAY Review: Object-Oriented Programming Mutable Lists Identity and Equality Mutable Dictionaries

5 R EVIEW : OOP C LASS D ESIGN At Hogwarts, we want to write a class to store information about potions. How would you represent the following attributes? Name of the potion. Ingredients of the potion. How it interacts with another potion. Collection of all potions ever. Instance Variable Class Variable Method CHOICES

6 R EVIEW : OOP C LASS D ESIGN At Hogwarts, we want to write a class to store information about potions. How would you represent the following attributes? Name of the potion: Instance variable Ingredients of the potion: Instance variable How it interacts with another potion: Method Collection of all potions ever: Class variable

7 R EVIEW : M UTABLE D ATA S TRUCTURES We have seen that objects possess state: they can change over time. Objects are thus mutable. The IRLists and IDicts we saw earlier were immutable, which means that once created, they could not be modified. Python has built-in list and dictionary data structures that are mutable.

8 M UTABLE L ISTS : A P RIMER >>> a = [3, 4, 5] >>> a[0] 3 >>> a[1:] [4, 5] >>> a[0] = 7 >>> a [7, 4, 5] Could not have done this with tuples! Slicing makes a new list.

9 M UTABLE L ISTS : A P RIMER >>> a [7, 4, 5] >>> a.append(10) >>> a [7, 4, 5, 10] >>> a.extend([2, 3]) >>> a [7, 4, 5, 10, 2, 3] >>> a[2:4] = [6, 8] [7, 4, 6, 8, 2, 3] >>> a.pop() 3 >>> a [7, 4, 6, 8, 2] >>> a.remove(8) [7, 4, 6, 2] None of these operations create new lists. They all update the same list. The slicing operator here does not make a new list. It refers to elements and positions in the original list.

10 M UTABLE L ISTS : A P RIMER >>> a [7, 4, 6, 2] >>> a[3] = a[0] >>> a [7, 4, 6, 7] >>> a.count(7) 2 >>> a.index(4) 1 >>> a.reverse() >>> a [7, 6, 4, 7] >>> a.sort() >>> a [4, 6, 7, 7] >>> a.insert(1, 3) >>> a [4, 3, 6, 7, 7] >>> del a[2] >>> a [4, 3, 7, 7] None of these operations create new lists. They all update the same list.

11 L IST C OMPREHENSIONS List comprehensions allow us to create new lists in the style of generator expressions. >>> a = [2, 4, 6] >>> b = [2*item for item in a] >>> b [4, 8, 12] 1. Take the list a. 2. Call each element item. 3. Add twice the element to the new list.

12 L IST C OMPREHENSIONS List comprehensions allow us to create new lists in the style of generator expressions. >>> a = [2, 4, 6] >>> b = [2*item for item in a if item > 3] >>> b [8, 12] 1. Take the list a. 2. Evaluate one element and call the result item. 3. Add twice the item to the new list… 4. … but only if item is greater than 3.

13 W ORKING WITH M UTABLE L ISTS Write a function called square_list that squares the items in a list. The function does not create a new list: it mutates the original list. (Assume the list is not deep.) >>> my_list = [2, 7, 1, 8, 2] >>> square_list(my_list) >>> my_list[1] 49 We are not creating a new list. We are not using the statement my_list = square_list(my_list)

14 W ORKING WITH M UTABLE L ISTS Write a function called square_list that squares the items in a list. The function does not create a new list: it mutates the original list. (Assume the list is not deep.) def square_list(l): pos = 0 while pos < len(l): l[pos] = l[pos] * l[pos] pos += 1 1. Initialize a variable that keeps track of the current position in the list. 2. As long as there are elements… 3. Update the current position in the list with the new value. 4. Move to the next position in the list. No return statement!

15 C OMPARING L ISTS AND T UPLES def square_tuple(tup): results = () for val in tup: results = results + (val*val,) return results def square_list(l): pos = 0 while pos < len(l): l[pos] = l[pos] * l[pos] pos += 1 A new tuple is created.The original list is modified. (Actually, new tuples are created in each iteration.) Items are added to the new tuple. The new tuple is returned.

16 W ORKING WITH M UTABLE L ISTS Write a function called map_list that maps the function provided to the items of a list. The function does not create a new list: it mutates the original list. >>> my_list = [2, 7, 1, 8, 2] >>> map_list(lambda x: x**3, my_list) >>> my_list[3] 512

17 W ORKING WITH M UTABLE L ISTS Write a function called map_list that maps the function provided to the items of a list. The function does not create a new list: it mutates the original list. def map_list(fn, l): pos = 0 while pos < len(l): l[pos] = __________ pos += 1

18 W ORKING WITH M UTABLE L ISTS Write a function called map_list that maps the function provided to the items of a list. The function does not create a new list: it mutates the original list. def map_list(fn, l): pos = 0 while pos < len(l): l[pos] = fn(l[pos]) pos += 1

19 A NNOUNCEMENTS : M IDTERM 2 Midterm 2 is on Wednesday, July 25. – Where? 2050 VLSB. – When? 7PM to 9PM. – How much? Material covered from July 4 until, and including, July 19 (from immutable trees until environment diagrams). You will also need to know material from Midterm 1. Closed book and closed electronic devices. One 8.5” x 11” ‘cheat sheet’ allowed. Group portion is 15 minutes long. Midterm review session on Friday, July 20.

20 A NNOUNCEMENTS : M IDTERM 1 Midterm 1 solutions will be released tonight. Midterm 1 regrade request protocol: – Attach, to the front, a sheet of paper describing the questions that you would like to be regraded, and the reasons why. – We reserve the right to regrade the entire midterm. – Regrade request deadline is end of day, Thursday, July 26.

21 A NNOUNCEMENTS Homework 8 is due Tuesday, July 17. Homework 9 is due Friday, July 20. Project 3 is due Tuesday, July 24. Please ask for help if you need to. There is a lot of work in the weeks ahead, so if you are ever confused, consult (in order of preference) your study group and Piazza, your TAs, and Jom. Don’t be confused!

22 B OX - AND -P OINTER D IAGRAMS my_list = [2, 7, 1, 8, 2] The boxes point to the elements of the list. This arrow shows the start of the list. Element 1 27 my_list 182 Element 2 Element 3Element 5 Element 4 The name of the list, which points to the list.

23 B OX - AND -P OINTER D IAGRAMS my_list = [2, [3, 1], 1, 8, 2] 2 my_list

24 I DENTITY AND E QUALITY >>> my_list = [2, 7, 1, 8, 2] >>> other_list = [2, 7, 1, 8, 2] >>> my_list == other_list True >>> my_list is other_list False 27 my_list other_list 182 my_list and other_list have the same values: they are equal. my_list and other_list are different lists: they are not identical.

25 I DENTITY AND E QUALITY >>> my_list = [2, 7, 1, 8, 2] >>> other_list = my_list >>> my_list == other_list True >>> my_list is other_list True my_list and other_list have the same values: they are equal. my_list and other_list are the same lists: they are identical. 27 my_list 182 other_list

26 I DENTITY AND E QUALITY >>> kaushik = Person(...) >>> kaushy = kaushik >>> kaushik is kaushy True >>> kaushik == kaushy True kaushik and kaushy are different names for the same object: they are identical. Since kaushik and kaushy are different names for the same object, they have the same value, and are equal. Identity implies equality.

27 I DENTITY AND E QUALITY >>> kaushik = Person(...) >>> shrivats = Person(...) >>> shrivats is kaushik False >>> shrivats == kaushik True kaushik and shrivats are names for different objects: they are not identical. kaushik and shrivats are names for different objects that have the “same value”, and are thus equal. Equality does not necessarily imply identity.

28 I DENTITY AND E QUALITY : C AVEAT By default, in Python, == acts the same as is. a == b is converted to a.__eq__(b) The Person class in the previous slide should implement the __eq__ method, or else shrivats == kaushik would have also evaluated to False. Classes can define what the “equality” of their instances means.

29 I DENTITY AND E QUALITY The classes for the native data types in Python (numbers, Booleans, strings, tuples, lists, dictionaries) implement the __eq__ method. >>> 3 == 4 False >>> [1, 2, 3] == [1, 2, 3] True >>> True.__eq__(False) False

30 I DENTITY AND E QUALITY : P RACTICE With the following expressions >>> a = [2, 7, 1, 8] >>> b = [3, 1, 4] >>> a[2] = b >>> c = [2, 7, [3, 1, 4], 8] what do the following expressions evaluate to? (A box-and-pointer diagram may be useful here.) >>> a[2][0] >>> a[2] is b >>> a is c >>> a == c

31 I DENTITY AND E QUALITY : P RACTICE With the following expressions >>> a = [2, 7, 1, 8] >>> b = [3, 1, 4] >>> a[2] = b >>> c = [2, 7, [3, 1, 4], 8] what do the following expressions evaluate to? (A box-and-pointer diagram may be useful here.) >>> a[2][0]2 >>> a[2] is bTrue >>> a is cFalse >>> a == cTrue

32 I DENTITY AND E QUALITY : P RACTICE With the following expressions >>> a = [2, 7, 1, 8] >>> b = [3, 1, 4] >>> a[2] = b >>> c = [2, 7, [3, 1, 4], 8] >>> a[2][1] = 3 what do the following expressions evaluate to? (A box-and-pointer diagram may be useful here.) >>> a[2][1] >>> b[1] >>> c[2][1]

33 I DENTITY AND E QUALITY : P RACTICE With the following expressions >>> a = [2, 7, 1, 8] >>> b = [3, 1, 4] >>> a[2] = b >>> c = [2, 7, [3, 1, 4], 8] >>> a[2][1] = 3 what do the following expressions evaluate to? (A box-and-pointer diagram may be useful here.) >>> a[2][1]3 >>> b[1]3 >>> c[2][1]1

34 I DENTITY AND E QUALITY : P RACTICE Implement the method __eq__ for the Pokemon class that will allow us to check if one Pokémon is “equal” to another, which means that it has the same HP as the other. >>> ashs_pikachu = Pokemon(‘Pikachu’, ‘Ash’, 300) >>> brocks_pikachu = Pokemon(‘Pikachu’, ‘Brock’, 300) >>> ashs_pikachu is brocks_pikachu False >>> ashs_pikachu == brocks_pikachu True

35 I DENTITY AND E QUALITY : P RACTICE Implement the method __eq__ for the Pokemon class that will allow us to check if one Pokémon is “equal” to another, which means that it has the same HP as the other. class Pokemon:... def __eq__(self, other): return _________________________________________

36 I DENTITY AND E QUALITY : P RACTICE Implement the method __eq__ for the Pokemon class that will allow us to check if one Pokémon is “equal” to another, which means that it has the same HP as the other. class Pokemon:... def __eq__(self, other): return self.get_hit_pts() == other.get_hit_pts()

37 S URVEY R ESPONSES Survey responses are generally very positive. “They have great pictures to help me learn.” “Love the breaks: come back attentive.” “Tom and Jon create a comfortable environment that invites questions.” “I actually look forward to coming to lecture.” “Needs more ponies.”

38 S URVEY R ESPONSES “Homework is more difficult than questions presented in lecture.” This is intentional! Lectures describe and explain the ideas; discussions and labs reinforce the ideas; homework and projects allow you to wrestle with, and learn, the material. “Please post the lecture slides earlier.” We will try and get them online by 9am, so that you have time to look over them if you need to. The answers to the questions will also be available soon after lecture.

39 S URVEY R ESPONSES “Class goes too fast.” Again, we apologize, but summer courses tend to go faster than normal. Please don’t hesitate to talk to your study group and the staff whenever you are stuck. Don’t be confused! “More practical examples in lecture.” We will try to include more practical examples. “Lectures are behind the homework.” Yes, but we have now caught up!

40 S URVEY R ESPONSES “Too many questions being asked in class.” We will try to address as many questions as we can without compromising on pace. Your questions are our constant feedback regarding whether the concept makes sense. So, keep asking questions! However, if the question is tangential, or relates to other languages like Java or C, we may defer the question to after class, or office hours, or Piazza. Don’t be afraid to ask questions! We will definitely address your question, even if not in lecture. However, you must re-ask it, on Piazza, so we remember to answer it.

41 H AIKU B REAK “I love comp science, Bring on the problem, baby This is what we do.” “CS not that hard. But sometimes it no make sense.” “Computer science, Solutions are ecstasy, Debugging is hell.” “This is a haiku. I do not want to write this. But now I am done.” “Class is good. I am learning lots. Keep it up.” “To describe CS With a short, succinct haiku. Out of syllables.”

42 M UTABLE D ICTIONARIES Lists allow us to index elements by integers; dictionaries allow us to index elements by keys that are not necessarily integers. This is particularly useful when we want to establish a correspondence between a descriptive key and a value.

43 M UTABLE D ICTIONARIES >>> roman_numerals = { ‘I’ : 1, ‘V’ : 5, ‘X’ : 10 } >>> roman_numerals[‘V’] 5 >>> roman_numerals.__getitem__(‘V’) 5 >>> list(roman_numerals.keys()) [‘I’, ‘V’, ‘X’] >>> ‘C’ in roman_numerals False Keys Values

44 M UTABLE D ICTIONARIES Write the function count_words, which returns a dictionary that maps a word to the number of times it occurs in a list of words. >>> word_list = [‘the’, ‘rain’, ‘in’, ‘spain’, ‘falls’, ‘mainly’, ‘in’, ‘the’, ‘plain’] >>> word_counts = count_words(word_list) >>> word_counts[‘the’] 2

45 M UTABLE D ICTIONARIES def count_words(l): count_dict = {} for word in l: if word not in count_dict: count_dict[word] = 1 else: count_dict[word] += 1 return count_dict 1. Create a new dictionary for the counts.2. For each word in the list of words If the word is not already in the dictionary Make a new entry for it. 5. Otherwise, update the existing entry.

46 C OMPARING D ICTIONARIES AND ID ICTS def count_words_idict(l): counts = make_idict() for word in l: count = idict_select(counts, word) if count is not None: counts = idict_update(counts, word, count+1) else: counts = idict_update(counts, word, 1) return counts New immutable dictionaries are created in each iteration.

47 M UTABLE D ICTIONARIES : P RACTICE Write a function tally_votes that takes in a list of tuples, each of which has two elements: a candidate for an election, and number of votes received by that candidate in a particular state. tally_votes will return a dictionary that maps a candidate to the number of votes received by the candidate. >>> votes = [(‘louis’, 30), (‘eva’, 45), (‘ben’, 4), (‘eva’, 30), (‘ben’, 6), (‘louis’, 15)] >>> total_votes = tally_votes(votes) >>> total_votes[‘ben’] 10

48 M UTABLE D ICTIONARIES : P RACTICE def tally_votes(votes): vote_dict = {} for vote in votes: candidate = _______ vote_count = _______ if ___________________________: _________________________________ else: __________________________________ return vote_dict

49 M UTABLE D ICTIONARIES : P RACTICE def tally_votes(votes): vote_dict = {} for vote in votes: candidate = vote[0] vote_count = vote[1] if candidate not in vote_dict: vote_dict[candidate] = vote_count else: vote_dict[candidate] += vote_count return vote_dict

50 OOP: C LASS M ETHODS Class variables are variables shared by all instances of a class: they are not specific to a particular instance. Methods are specific to a particular instance. Occasionally, it would be useful to have a method that is independent of any instance, but relevant to the class as a whole.

51 OOP: C LASS M ETHODS Suppose that we want to maintain a trainer directory in our Pokemon class, which would allow us to find the list of trainers that own a certain Pokémon. This is not specific to a particular Pokemon object. As with total_pokemon, this is relevant to the Pokemon class as a whole.

52 OOP: C LASS M ETHODS class Pokemon: total_pokemon = 0 trainer_dir = {} def __init__(self, name, owner, hp):... if name not in Pokemon.trainer_dir: Pokemon.trainer_dir[name] = [owner] else: Pokemon.trainer_dir[name].append(owner)

53 OOP: C LASS M ETHODS We define a class method (or a static method) that takes in the name of a Pokémon and returns a list of the trainers that own that Pokémon. We use the staticmethod decorator. class def trainers(name): if name in Pokemon.trainer_dir: return Pokemon.trainer_dir[name] return None

54 OOP: C LASS M ETHODS >>> mistys_togepi = Pokemon('Togepi', 'Misty', 245) >>> ashs_pikachu = ElectricPokemon('Pikachu', 'Ash', 300) >>> brocks_pikachu = ElectricPokemon('Pikachu', 'Brock', 300) >>> Pokemon.trainers('Pikachu') ['Ash', 'Brock'] >>> Pokemon.trainers('Charmander')

55 C ONCLUSION Python has built-in mutable lists and dictionaries. These can be mutated, which means that the original lists and dictionaries are modified. There are two different kinds of equality: one that checks if two objects are the same (identical), and one that checks if two objects have the same characteristics or values (equal). The second kind of equality can be defined by the class. OOP allows us to have methods that are relevant to the whole class, not just to specific instances. Preview: Mutable recursive lists and environment diagrams.