CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.

Slides:



Advertisements
Similar presentations
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?
Advertisements

CS61A Lecture 25 Delayed Sequences Jom Magrotker UC Berkeley EECS July 31, 2012.
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
CS61A Lecture 4 Higher Order Functions Tom Magrino and Jon Kotker UC Berkeley EECS June 21, 2012.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Slide 1 CS3 Fall 2005 Lecture week 13: Introduction to the Big Project.
CS107 Introduction to Computer Science Lecture 5, 6 An Introduction to Algorithms: List variables.
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
CS61A Lecture 3 Higher Order Functions Jon Kotker and Tom Magrino UC Berkeley EECS June 20, 2012.
UC Berkeley EECS Head TA Michael Ball The Beauty and Joy of Computing Beyond Blocks Python Session 2: Data Structures UC Berkeley EECS TA Peter Sujan (thanks.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
CS61A Disc 3 Sections 13/26 Dickson Tsai No OH this week. Schedule appts at dicksontsai.com/meet 1.
CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.
CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
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.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
CIT 590 Intro to Programming Lecture 4. Agenda Doubts from HW1 and HW2 Main function Break, quit, exit Function argument names, scope What is modularity!
Lecture 3.4: Recursive Algorithms CS 250, Discrete Structures, Fall 2011 Nitesh Saxena *Adopted from previous lectures by Zeph Grunschlag.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
Fall 2008Programming Development Techniques 1 Topic 5 Data Abstraction Note: This represents a change in order. We are skipping to chapter 2 without finishing.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
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.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
CS61A Lecture 1 Introduction and Basics Tom Magrino and Jon Kotker UC Berkeley EECS June 18, 2012.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
CS61A Lecture 29 Parallel Computing Jom Magrotker UC Berkeley EECS August 7, 2012.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
Abstraction A way of managing complexity for large programs A means of separating details of computation from use of computation Types of Abstraction Data.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Algorithmic complexity: Speed of algorithms
Pairs and Lists. Data Abstraction. SICP: Sections – 2.2.1
Intro to Computer Science CS1510 Dr. Sarah Diesburg
6.001 SICP Data abstractions
Important Concepts from Clojure
Important Concepts from Clojure
CISC101 Reminders Slides have changed from those posted last night…
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
CS190/295 Programming in Python for Life Sciences: Lecture 6
CMSC201 Computer Science I for Majors Lecture 12 – Tuples
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Lecture #6 מבוא מורחב.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Algorithmic complexity: Speed of algorithms
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Lecture #7 מבוא מורחב.
Important Concepts from Clojure
CHAPTER 4: Lists, Tuples and Dictionaries
Today’s topics Abstractions Procedural Data
Algorithmic complexity: Speed of algorithms
Introduction to Strings
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Presentation transcript:

CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012

2 C OMPUTER S CIENCE IN THE N EWS

3 T ODAY Quick orders of growth review Data Abstraction and making new Abstract Data Types Tuples

4 R EVIEW : O RDERS OF G ROWTH What is the order of growth (using Θ notation) for the following Python function? def foo(x): if x < 3: return x return foo(x % 3) + foo(x – 1)

5 R EVIEW : O RDERS OF G ROWTH Θ(n) We know that the result of n % 3 is 0, 1, or 2 (the base case), so we know that the first recursive call will always result in a base case and we can treat it as a constant time operation. The second recursive call will take (about) n recursive calls before reaching a base case (we subtract one from n each time). So we have Θ(n) recursive calls with constant amount of work done for each call.

6 D ATA A BSTRACTION We want to be able to think about data in terms of its meaning rather than in terms of the way it is represented. Data abstraction allows us to isolate: – How the data is represented (as parts) – How the data is manipulated (as units) We do this by using functions to help create a division between these two cases.

7 P ROBLEM : R ATIONAL N UMBERS

8 Constructor Selectors These are all we need to define an Abstract Data Type (ADT).

9 P ROBLEM : R ATIONAL N UMBERS def mul_rats(r1, r2): return make_rat(numer(r1) * numer(r2), denom(r1) * denom(r2)) def add_rats(r1, r2): n1, d1 = numer(r1), denom(r1) n2, d2 = numer(r2), denom(r2) return make_rat(n1 * d2 + n2 * d1, d1 * d2) def eq_rats(r1, r2): return numer(r1) * denom(r2) == numer(r2) * denom(r1) Notice that we don’t have to know how rational numbers work in order to write any code that uses them!

10 P ROBLEM : R ATIONAL N UMBERS Great! If we can implement make_rat, numer, and denom, then we can finish our wonderful rational numbers module!

11 How would I write a function to invert (flip) a rational number using the constructor and selectors we are using for rational numbers? P RACTICE : U SING A BSTRACTIONS

12 How would I write a function to invert (flip) a rational number using the constructor and selectors we are using for rational numbers? def invert_rat(r): return make_rat(denom(r), numer(r)) P RACTICE : U SING A BSTRACTIONS

13 T UPLES : O UR F IRST D ATA S TRUCTURE Tuples are a built-in datatype in Python for representing a constant sequence of data. >>> pair = (1, 2) >>> pair[0] 1 >>> pair[1] 2 >>> x, y = pair >>> x 1 >>> y 2 >>> z = pair + (6, 5, 4) >>> z (1, 2, 6, 5, 4) >>> len(z) 5 >>> z[2:5] (6, 5, 4) >>> triplet = (1,...2,...3) >>> triplet (1, 2, 3) >>> for num in triplet:... print(num, “potato”)... 1 potato 2 potato 3 potato >>> (1) 1 >>> (1,) (1,)

14 T UPLES : O UR F IRST D ATA S TRUCTURE The Python data type tuple is an example of what we call a data structure in computer science. A data structure is a type of data that exists primarily to hold other pieces of data in a specific way.

15 Write the higher order function map, which takes a function, fn, and a tuple of values, vals, and returns the tuple of results of applying fn to each value in vals. >>> map(square, (1, 2, 3, 4, 5)) (1, 4, 9, 16, 25) P RACTICE : U SING T UPLES AND A BSTRACTIONS

16 Write the higher order function map, which takes a function, fn, and a tuple of values, vals, and returns a the tuple of results of applying fn to each value in vals. def map(fn, vals): results = () for v in vals: results = results + (fn(v),) return results P RACTICE : U SING T UPLES AND A BSTRACTIONS

17 A NNOUNCEMENTS Project 1 autograder is running now. Next week, we will move to 105 Stanley for the rest of the summer. Midterm 1 is on July 9. – We will have a review session closer to the date. If you need accommodations for the midterm, please notify DSP by the end of this week. HW1 grade should be available on glookup.

18 P ROBLEM : R ATIONAL N UMBERS def make_rat(n, d): return (n, d) def numer(x): return x[0] def denom(x): return x[1]

19 A BSTRACTION D IAGRAMS make_rat, numer, denomtuple, getitem rational numbers as numerators and denominators rational numbers as tuples tuples as sequences of data However Python implements tuples Abstraction Barrier Using the ADT Implementing the ADT Using the ADT Implementing the ADT Abstraction Barrier

20 D ATA A BSTRACTION : S O W HAT ? It makes code more readable and intuitive. Which version is clearer? def mul_rats(r1, r2): return (r1[0] * r2[0], r1[1] * r2[1]) def mul_rats(r1, r2): return (r1[0] * r2[0], r1[1] * r2[1]) def mul_rats(r1, r2): return make_rat(numer(r1) * numer(r2), denom(r1) * denom(r2)) def mul_rats(r1, r2): return make_rat(numer(r1) * numer(r2), denom(r1) * denom(r2)) When we write code that assumes a specific implementation of our ADT, we call this a data abstraction violation (DAV).

21 D ATA A BSTRACTION : S O W HAT ? We don’t have to worry about changing all the code that uses our ADT if we decide to change the implementation! def make_rat(n, d): return (d, n) def numer(x): return x[1] def denom(x): return x[0] # Will still work def mul_rats(r1, r2): return make_rat(numer(r1) * numer(r2), denom(r1) * denom(r2)) # Will still work def mul_rats(r1, r2): return make_rat(numer(r1) * numer(r2), denom(r1) * denom(r2)) # Will break def mul_rats(r1, r2): return (r1[0] * r2[0], r1[1] * r2[1]) # Will break def mul_rats(r1, r2): return (r1[0] * r2[0], r1[1] * r2[1])

22 P RACTICE : D ATA A BSTRACTION Suppose that Louis Reasoner wrote the following function prod_rats that takes a tuple of rational numbers using our ADT and returns their product. Correct his code so that he does not have any data abstraction violations. def prod_rats(rats): total, i = (1, 1), 0 while i < len(rats): total = (total[0] * rats[i][0], total[1] * rats[i][1]) i += 1 return total

23 P RACTICE : D ATA A BSTRACTION Suppose that Louis Reasoner wrote the following function prod_rats which takes a tuple of rational numbers using our ADT and returns their product. Correct his code so that he does not have any data abstraction violations. def prod_rats(rats): total, i = make_rat(1, 1), 0 while i < len(rats): total = make_rat(numer(total) * numer(rats[i]), denom(total) * denom(rats[i])) i += 1 return total

24 P RACTICE : D ATA A BSTRACTION Say I wrote the following functions to define my student ADT. def make_student(name, id): return (name, id) def student_name(s): return s[0] def student_id(s): return s[1] If I changed the student ADT to also include the student’s age, what functions would I have to add or change in order to complete the abstraction?

25 P RACTICE : D ATA A BSTRACTION Say I wrote the following functions to define my student ADT. def make_student(name, id): return (name, id) def student_name(s): return s[0] def student_id(s): return s[1] If I changed the student ADT to also include the student’s age, what functions would I have to add or change in order to complete the abstraction? You would have to change make_student to take this new parameter. If you just represent a student as the tuple (name, id, age), then you only have to add a selector for the student’s age. The other two selectors would not have to be modified in this case.

26 C ONCLUSION Tuples are a nice way to group data in Python. Learned how to design new types of data by using data abstraction. Preview: Useful data structures.

27 E XTRAS : U SING F UNCTIONS TO C REATE ADT S It turns out you don’t need to have something like tuples in a language in order to group data together. Say I wanted to make a pair abstraction, which is like a tuple of length 2. I could do this with just functions: def make_pair(first, second): def pair(msg): if msg == “first”: return first elif msg == “second”: return second return pair def first(p): return p(“first”) def second(p): return p(“second”)

28 E XTRAS : M ORE ABOUT S TRINGS Strings and tuples are both sequences, meaning that they are things that you can iterate over with a for loop. Interestingly, they can also be indexed into and sliced like tuples. >>> for letter in “abc”:... print(letter) a b c >>> “asdf”[2] d >>> “slaughterhouse”[1:9] “laughter”