CSE : Python Programming

Similar documents
CSE : Python Programming

CSE : Python Programming

Sets. identity maps, unordered collection

Python for C programmers

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

CIS192: Python Programming

Intro. Speed V Growth

Python Programming: Lecture 3 Functions

CIS192 Python Programming

TAIL RECURSION, SCOPE, AND PROJECT 4 11

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

CIS192 Python Programming

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

SD314 Outils pour le Big Data

Functional Languages. Hwansoo Han

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

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

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

Programming Language Pragmatics

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Measuring Efficiency

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

CS 11 Haskell track: lecture 1

LECTURE 16. Functional Programming

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CSCE 314 Programming Languages

4. Functional Programming Language-Oriented Programming

Concepts of Programming Languages

peval Documentation Release Bogdan Opanchuk

Chapter 11 :: Functional Languages

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

SCHEME AND CALCULATOR 5b

6.001 Notes: Section 8.1

Functional Programming

CS1 Lecture 5 Jan. 25, 2019

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19

Introduction to Python Code Quality

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

CSC 326H1F, Fall Programming Languages. What languages do you know? Instructor: Ali Juma. A survey of counted loops: FORTRAN

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

CSE 341 Lecture 27. JavaScript scope and closures. slides created by Marty Stepp

Scheme: Expressions & Procedures

CS 360 Programming Languages Interpreters

CS457/557 Functional Languages

Programming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Ruby: Introduction, Basics

CS1 Lecture 5 Jan. 26, 2018

Week 2: The Clojure Language. Background Basic structure A few of the most useful facilities. A modernized Lisp. An insider's opinion

Lecture 5: Lazy Evaluation and Infinite Data Structures

CSE 341, Autumn 2015, Ruby Introduction Summary

Logo Features We'll first present a sample Logo program, and then discuss each component separately.

CMSC 330: Organization of Programming Languages

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Advanced topics, part 2

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CS116 - Module 5 - Accumulative Recursion

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CSE 341: Programming Languages

CSC324 Functional Programming Efficiency Issues, Parameter Lists

CSCC24 Functional Programming Scheme Part 2

HIGHER ORDER FUNCTIONS 2

Programming Languages

Functions parameters, scope CS GMU

Environments

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

CS1 Lecture 15 Feb. 18, 2019

Functional programming in LISP

CSE 505: Concepts of Programming Languages

6.001 Notes: Section 6.1

CS 11 python track: lecture 4

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

CSC148 winter stools, names, tracing week 5

61A Lecture 2. Friday, August 28, 2015

Organization of Programming Languages CS3200/5200N. Lecture 11

Ruby: Introduction, Basics

Lecture 16: Static Semantics Overview 1

Stop coding Pascal. Saturday, April 6, 13

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

CSE341: Programming Languages Lecture 15 Macros. Zach Tatlock Winter 2018

What is a macro. CSE341: Programming Languages Lecture 15 Macros. Example uses. Using Racket Macros. Zach Tatlock Winter 2018

Programming Paradigms

Lecture 8. Conditionals & Control Flow

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

Functional Programming. Big Picture. Design of Programming Languages

Onion Language Reference Manual. By: Andrew Aday, (aza2112) Amol Kapoor (ajk2227), Jonathan Zhang (jz2814)

Lecture 13 CIS 341: COMPILERS

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

CSCI B522 Lecture 11 Naming and Scope 8 Oct, 2009

To figure this out we need a more precise understanding of how ML works

CSE 341: Programming Languages

Higher Order Functions

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Streams and Evalutation Strategies

Transcription:

CSE 399-004: Python Programming Lecture 10: Functional programming, Memoization March 26, 2007 http://www.seas.upenn.edu/~cse39904/

Announcements Should have received email about meeting times Length: ~15 minutes (try to show up on time!) Purpose: Give a high level overview of what you're doing Basic data structures and classes How do they interact What would you like my opinion on? Again, this is fairly informal Come prepared to talk and explain But no need to have anything like slides prepared 2

Functional programming

A quick survey Who has programmed in: Scheme Lisp Standard ML OCaml Haskell Some other functional language? 4

A quick survey Who has programmed in: Scheme Lisp What makes these languages "functional?" Standard ML OCaml Haskell Some other functional language? 4

A quick survey Who has programmed in: Scheme Lisp Standard ML OCaml What makes these languages "functional?" Better question: What's a dysfunctional language? Haskell Some other functional language? 4

What is functional programming? Depends on who you ask Two important features (in my mind): Minimal (or no!) use of mutating assignment Higher-order functions: Functions that take other functions as arguments Popular functional languages tend to also be strongly typed: types are checked at compile time and there are no implicit coercions 5

Why care about functional prog.? Standard answer: Reasoning about mutation is hard If we don't mutate anything, then everything acts as it would in pure mathematics A similar reason underlies why global state is bad Another answer: It's "more elegant" if functions are "firstclass", meaning that we can treat them like any other piece of data 6

Is Python a functional language? Depends on your coding style Mutating state seems to be a very common thing in Python programming: You want to modify structures Object-oriented programming, in practice, seems to also favor mutation Even if you think it's a functional language, "real" functional languages tend to be a bit more expressive 7

>>> q = [2, 3] >>> p = [1, q, 4] >>> print p [1, [2, 3], 4] >>> q[0] = 42 >>> print q [42, 3] >>> print p [1, [42, 3], 4] These first two assignments are fine, as far as functional programming is concerned. q 2 3 8

>>> q = [2, 3] >>> p = [1, q, 4] >>> print p [1, [2, 3], 4] >>> q[0] = 42 >>> print q [42, 3] >>> print p [1, [42, 3], 4] These first two assignments are fine, as far as functional programming is concerned. Makes me cringe to say that, because of iteration constructs q 2 3 8

>>> q = [2, 3] >>> p = [1, q, 4] >>> print p [1, [2, 3], 4] >>> q[0] = 42 >>> print q [42, 3] >>> print p [1, [42, 3], 4] p 1 4 q 2 3 9

>>> q = [2, 3] >>> p = [1, q, 4] >>> print p [1, [2, 3], 4] >>> q[0] = 42 >>> print q [42, 3] >>> print p [1, [42, 3], 4] p 1 4 q 42 3 10

>>> q = [2, 3] >>> p = [1, q, 4] >>> print p [1, [2, 3], 4] >>> q[0] = 42 >>> print q [42, 3] >>> print p [1, [42, 3], 4] This is the kind of assignment statement that functional programming avoids. The difference? Making a variable simply point to a (new) data structure versus modifying a data structure in place. 11

>>> q = [2, 3] >>> p = [1, q, 4] >>> print p [1, [2, 3], 4] >>> q[0] = 42 >>> print q [42, 3] >>> print p [1, [42, 3], 4] >>> p = [3, 4] This assignment is fine, as far as functional programming is concerned. The difference? Making a variable simply point to a (new) data structure versus modifying a data structure in place. 12

Nested functions >>> def foo(x, y):... def bar():... return y.append(x+2)... return bar... >>> zs = [2, 3] >>> f = foo(2, zs) >>> f() >>> zs [2, 3, 4] >>> zs.append(5) >>> zs [2, 3, 4, 5] >>> f() >>> zs [2, 3, 4, 5, 4] What happened here? bar doesn't define y, x x, y are not global So x, y are free in bar They must refer to the nearest enclosing scope, i.e., foo 13

Nested functions >>> def foo(x, y):... def bar():... return y.append(x+2)... return bar... >>> zs = [2, 3] >>> f = foo(2, zs) >>> f() >>> zs [2, 3, 4] >>> zs.append(5) >>> zs [2, 3, 4, 5] >>> f() >>> zs [2, 3, 4, 5, 4] When bar is returned from foo, it's packed up in an environment defining x, y Not a namespace, but the idea is similar When bar is executed, execute it in that environment 14

Nested functions >>> def foo(x, y):... def bar():... return y.append(x+2)... return bar... >>> zs = [2, 3] >>> f = foo(2, zs) >>> f() >>> zs [2, 3, 4] >>> zs.append(5) >>> zs [2, 3, 4, 5] >>> f() >>> zs [2, 3, 4, 5, 4] In the context of functional programming, it's important that we be able to construct new functions at run-time 15

Passing functions to other functions >>> def gt(x, y):... if x > y:... return -1... elif x == y:... return 0... else:... return 1... >>> print sorted([10, 20, 4, 50]) [4, 10, 20, 50] >>> print sorted([10, 20, 4, 50], cmp = gt) [50, 20, 10, 4] 16

Passing functions to other functions >>> def snd(x):... return x[1]... >>> a = [(20, 5), (10, 10), (30, 40), (70, 2)] >>> print sorted(a) [(10, 10), (20, 5), (30, 40), (70, 2)] >>> print sorted(a, key = snd) [(70, 2), (20, 5), (10, 10), (30, 40)] 17

Lambda forms >>> a = [(20, 5), (10, 10), (30, 40), (70, 2)] >>> print sorted(a) [(10, 10), (20, 5), (30, 40), (70, 2)] >>> print sorted(a, key = lambda x: x[1]) [(70, 2), (20, 5), (10, 10), (30, 40)] 18

Lambda forms In Python, we can define nameless functions using the lambda keyword lambda arg1, arg2,... : expr The "expr" there is key: Only expressions are allowed, i.e., those constructs which evaluate to a value For example, no assignments or blocks Anonymous lambdas in "real" functional languages are, under the covers, how all functions are defined 19

Lambda forms lambda arg1, arg2,... : expr The "expr" there is key: Only expressions are allowed, i.e., those constructs which evaluate to a value Another point about functional programming Everything has a value! We don't evaluate something for its side-effects What's the value of an if statement or a while loop in Python? 20

Common higher-order functions map(f, a) filter(p, a) [ f(x) for x in a ] [ x for x in a if p(x) ] >>> reduce(lambda x, y : x ** y, [4, 3, 2, 1]) 4096 >>> reduce(lambda x, y : x + y, [4, 3, 2, 1]) 10 21

Common higher-order functions map(f, a) filter(p, a) [ f(x) for x in a ] [ x for x in a if p(x) ] >>> reduce(lambda x, y : x ** y, [4, 3, 2, 1]) 4096 >>> reduce(lambda x, y : x + y, [4, 3, 2, 1]) 10 "Real" functional languages call this "fold". 21

Partial applications >>> def f(x, y):... return x + y... >>> f(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() takes exactly 2 arguments (1 given) Python doesn't let you partially apply functions, another common feature in "real" functional languages. 22

Perhaps I'm too hard on Python Just because there are a number of things which "real" functional languages "do better", that doesn't mean it's pointless to avoid functional programming in Python The benefits are all there in Python You just may not have as expressive constructs as you might like to make it feel entirely natural 23

Memoization

Recursion versus iteration def fib_iter(n) : a, b = 0, 1 for i in range(0, n - 1): a, b = b, a + b return a Fast, but a bit hard to make sense of. Very close to mathematical definition, but very slow. def fib_rec(n) : if n <= 1: return n else: return fib(n - 1) + fib(n - 2) 25

Recursion versus iteration def fib_iter(n) : a, b = 0, 1 for i in range(0, n - 1): a, b = b, a + b return a Functional programming prefers recursion. (What's that i in the for loop doing?) def fib_rec(n) : if n <= 1: return n else: return fib(n - 1) + fib(n - 2) 25

fib(5) fib(4) fib(3) fib(3) fib(2) fib(1) fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) fib(2) fib(1) fib(0) 26

fib(5) fib(4) fib(3) fib(3) fib(2) fib(1) fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) fib(2) fib(1) fib(0) 26

fib(5) fib(4) fib(3) fib(3) fib(2) fib(1) fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) fib(2) fib(1) fib(0) 26

Memoized version of fib def fib_mem(n, ans = {}) : if n in ans: return ans[n] if n <= 1: ans[n] = n else: ans[n] = fib_mem(n - 1) + fib_mem(n - 2) return ans[n] 27

Memoized version of fib def fib_mem(n, ans = {}) : if n in ans: return ans[n] if n <= 1: ans[n] = n else: ans[n] = fib_mem(n - 1) + fib_mem(n - 2) return ans[n] We use ans here to keep track of the results of previous calls to fib_mem. Users should never supply a value for this argument. 27

Memoized version of fib def fib_mem(n, ans = {}) : if n in ans: return ans[n] if n <= 1: ans[n] = n else: ans[n] = fib_mem(n - 1) + fib_mem(n - 2) return ans[n] Recall that the value of this default argument is initialized once, when the function is defined. All the modifications in the function update the value. 28

Memoized version of fib def fib_mem(n, ans = {}) : if n in ans: return ans[n] if n <= 1: ans[n] = n else: ans[n] = fib_mem(n - 1) + fib_mem(n - 2) return ans[n] Downside: We've traded off memory usage for speed. (Also: is this in the spirit of functional programming?) 29