Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Similar documents
Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

Iterators & Generators

CSC148 Intro. to Computer Science

ITP Programming Languages Chapter 2 Building Abstractions with Data 2.5 Object-Oriented Programming 1. Polymorphism repr, str Interface

Beyond Blocks: Python Session #1

String Representations

61A LECTURE 14 MULTIPLE REPRESENTATIONS

61A LECTURE 14 MULTIPLE REPRESENTATIONS. Steven Tang and Eric Tzeng July 17, 2013

Python for C programmers

CS61A Lecture 21. Amir Kamil UC Berkeley March 11, 2013

Lecture #21: Search Trees, Sets. Last modified: Tue Mar 18 18:15: CS61A: Lecture #21 1

PIC 16: Iterators and Generators

Structure and Interpretation of Computer Programs

CIS192 Python Programming

MEMOIZATION, RECURSIVE DATA, AND SETS

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

Lecture 27: Streams and Lazy Evaluation

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

61A Lecture 3. Friday, September 5

Harness the power of Python magic methods and lazy objects.

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

CIS192 Python Programming

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

The Pyth Language. Administrivia

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Final Exam Version A

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

Sequence Types FEB

CIS192 Python Programming

Lecture #24: Programming Languages and Programs

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

CS1 Lecture 3 Jan. 18, 2019

Python 1: Intro! Max Dougherty Andrew Schmitt

CS1 Lecture 3 Jan. 22, 2018

Advanced Python. Executive Summary, Session 1

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Intro. Scheme Basics. scm> 5 5. scm>

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Lecture #23: Conversion and Type Inference

61A Lecture 16. Wednesday, October 5

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Lecture #14: OOP. Last modified: Mon Feb 27 15:56: CS61A: Lecture #14 1

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Lecture #10: Sequences. Last modified: Mon Feb 22 16:33: CS61A: Lecture #10 1

Jython. secondary. memory

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Artificial Intelligence A Primer for the Labs

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

Sample midterm 1 #1. Problem 1 (What will Scheme print?).

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

Structure and Interpretation of Computer Programs

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Python Tutorial. Day 1

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

Structure and Interpretation of Computer Programs

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python. Executive Summary

pygtrie Release Jul 03, 2017

Algorithms in Systems Engineering ISE 172. Lecture 5. Dr. Ted Ralphs

STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS >>> COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY REVIEW: INTERPRETATION 7/26/2012 READ PRINT

INTERPRETERS AND TAIL CALLS 9

Python for Finance. Advanced Features. Andras Niedermayer

CS 360: Programming Languages Lecture 12: More Haskell

Overloading, Type Classes, and Algebraic Datatypes

STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY 7/26/2012

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators

CS61A Notes Week 13: Interpreters

Software Development Python (Part B)

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

RLISTS AND THE ENVIRONMENT MODEL 9

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Objects. say something to express one's disapproval of or disagreement with something.

SCHEME AND CALCULATOR 5b

TUPLES AND RECURSIVE LISTS 5

CS61A Lecture 23 Py. Jom Magrotker UC Berkeley EECS July 26, 2012

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5'

Lecture #7: Recursion (and a data structure)

A Class to Manage Large Ensembles and Batch Execution in Python

CIS192 Python Programming

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

Structure and Interpretation of Computer Programs Summer 2014 Midterm 1

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Structure and Interpretation of Computer Programs

CSE : Python Programming

Comp Exam 1 Overview.

15-780: Problem Set #3

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Data Structures I: Linked Lists

Transcription:

Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1

Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of the kth occurrence of x (k>=0), or None if there isn t one.""" for i in range(len(l)): if L[i] == x: if k == 0: return i k -= 1 This same function works on lists, tuples, strings, and (if the keys are consecutive integers) dicts. In fact, it works for any list L for which len and indexing work as they do for lists and tuples. That is, find is generic in the type of L. Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 2

Duck Typing A statically typed language (such as Java) requires that you specify a type for each variable or parameter, one that specifies all the operations you intend to use on that variable or parameter. To create a generic function, therefore, your parameters types must be subtypes of some particular interface. You can do this in Python, too, but it is not a requirement. In fact, our find function will work on any object that has len and getitem, regardless of the object s type. This property is sometimes called duck typing: This parameter must be a duck, and if it walks like a duck and quacks like a duck, we ll say it is a duck. Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 3

Example: The repr Method Whentheinterpreterprintsthevalueofanexpression,itmustfirst convert that value to a (printable) string. To do so, it calls the repr () method of the value, which is supposed to return a string that suggests how you d create the value in Python. >>> "Hello" Hello >>> print(repr("hello")) Hello >>> repr("hello") # What does the interpreter print? (As a convenience, the built-in function repr(x) calls the repr method.) User-defined classes can define their own repr method to control how the interpreter prints them. Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 4

Example: The str Method Whentheprintfunctionprintsavalue,itcallsthe str ()method to find out what string to print. The constructor for the string type, str, does the same thing. Again, you can define your own str on a class to control this behavior. (The default is just to call repr ) >>> class rational:... def init (self, num, den):...... def str (self):... if self.numer() == 0: return "0"... elif self.denom() == 1: return str(self.numer())... else: return "{0}/{1}".format(self.numer(), self.denom())... def repr (self):... return "rational({}, {})".format(self.numer(), self.denom())... >>> print(rational(3,4)) 3/4 >>> rational(3,4) rational(3, 4) >>> print(rational(5, 1)) 5 Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 5

Aside: A Small Technical Issue str, repr, and print all call the methods str and repr, ignoring any instance variables of those names. For example, >>> v = rational(3, 4) >>> v. str <bound method rational. str of...> >>> v. str = lambda x: "FOO!" >>> # str is now an instance variable of v as well as a >>> # a method of class rational. >>> v. str <function <lambda> at...> >>> str(v) 3/4 >>> c. str () FOO! How could you implement str to do this? Hint: As in the homework, type(x) returns the class of x. Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 6

Other Generic Method Names Just as defining str allows you to specify how your class is printed, Python has many other generic connections to its syntax, which allow programmers great flexibility in expressing things. For example, Method Implements getitem (S, k) S[k] setitem (S, k, v) S[k] = v len (S) len(s) bool (S) bool(s) True or False add (S, x) S + x sub (S, x) S - x mul (S, x) S * x ge (S, x) S >= x... getattr (S, N ) S.N Attributes setattr (S, N, v) S.N = v Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 7

Iterators and Iterables The for statement is actually a generic control construct with the following meaning: for x in C: S tmp iter = iter(c) try: while True: x = tmp iter. next () S except StopIteration: pass Types for which iter works are called iterable, and those that implement next are iterators (returned by calling iter on an iterable). The built-in iter function first tries calling the method iter on the object, so if you define a class containing def iter (self):..., you ll have an iterable class. Inaddition,atypeisconsiderediterableifitimplements getitem, the method that implements the a[...] operator. Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 8

The Many Uses of Iterables Python cleanly integrates iterables into many contexts, showing the power of a good abstraction. The obvious: for x in aniterable:... L = [ f(x) for x in aniterable] Many functions take iterables as arguments rather than just lists: list(aniterable) set(aniterable) map(f, aniterable) sum(aniterable) max(aniterable) all(aniterable) Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 9