The building blocks of functional computing data, sequences conditionals recursion CS 121 today List Comprehensions map and applications.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Lilian Blot Recursion Autumn 2012 TPOP 1. Lilian Blot Recursion Autumn 2012 TPOP 2.
Map and Fold Building Powerful Abstractions. Hello. I’m Zach, one of Sorin’s students.
Structured programming
HW 1: Problems 3 & 4 EC 1 & 2.
Genome Sciences 373 Genome Informatics Quiz Section 2 April 7, 2015.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Recursion. Sum a list of numbers Iterative def sum(L): total = 0 for i in L: total += i return total Recursive def sum(L): if len(L) == 0: return 0 else:
CSC 1701B Computing: Science and Creativity. Outline  Types  Variables  Operators  Control: sequence, selection, repetition  Functions (block headings.
Welcome to CS 5! Be sure to watch your head…. A recursive spiral …
IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to.
Final Exam ~ notes On the semester’s material, with an attempt at bridging different topics. You may use two double-sided pages of notes (similar to before)…
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Programming Training Main Points: - Lists / Arrays in Python. - Fundamental algorithms on Arrays.
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
8 For-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
EECS 110: Lec 5: List Comprehensions Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
CS101 Computer Programming I Chapter 4 Extra Examples.
EECS 110: Lec 4: Functions and Recursion Aleksandar Kuzmanovic Northwestern University
CS 121 Today Fractals and Turtles! The Koch Curve how random…
IS 313 Tomorrow… IS 313 Today? 9/16/09 - today: recursion and beyond! 9/23/09 - next wk: no meeting (DC) 9/30/09 - following wk: for & while Homework functions.
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
 Problems  Rock-Paper-Scissors (fair game)  Functions Frenzy  Extra Problems  Pig Latin  Scoring Paper.
Loops ! We've seen variables change in-place before: [ x*6 for x in range(8) ] [ 0, 6, 12, 18, 24, 30, 36, 42 ] remember range ?
CompSci Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
EECS 110: Lec 10: Definite Loops and User Input Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
Recursion on Lists Lecture 5, Programmeringsteknik del A.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
EECS 110: Lec 9: Review for the Midterm Exam Aleksandar Kuzmanovic Northwestern University
The last CS 5 lecture you’ll ever need! Inducing labor for the machine! == Reducing labor for humans! On Warner Brothers' insistence, we affirm that this.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
Recursion Higher Order Functions CSCE 314 Spring 2016.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
CS 121 Today Fractals and Turtles! The Koch Curve how random…
EECS 110: Lec 10: Definite Loops and User Input
EECS 110: Lec 17: Review for the Final Exam
EECS 110: Lec 9: Review for the Midterm Exam
Algorithmic complexity: Speed of algorithms
EECS 110: Lec 5: List Comprehensions
EECS 110: Lec 5: List Comprehensions
EECS 110: Lec 6: Fractals and Trutles
EECS 110: Lec 4: Functions and Recursion
Announcements Final Exam on August 17th Wednesday at 16:00.
Another problem to solve…
EECS 110: Lec 10: Definite Loops and User Input
Recursion UW CSE 160 Winter 2017
Recursion Spring 2015 UW CSE 160
Recursion UW CSE 160 Spring 2018
Another problem to solve…
EECS 110: Lec 4: Functions and Recursion
Algorithmic complexity: Speed of algorithms
Recursion UW CSE 160 Winter 2016
Algorithmic complexity: Speed of algorithms
List Comprehensions Problem: given a list of prices, generate a new list that has a 20% discount to each. Formally: input: list of old prices; output:
Another problem to solve…
Recursion Review Spring 2019 CS 1110
Random numbers What does it mean for a number to be random?
functions are also data! other functions as input!
Unit Testing.
Presentation transcript:

The building blocks of functional computing data, sequences conditionals recursion CS 121 today List Comprehensions map and applications

functional programming >>> 'fun' in 'functional' True Key ideas in functional programming create small building blocks (functions) leverage self-similarity (recursion) representation via list structures (data) Compose these together to solve or investigate problems. elegant and concise not maximally efficient for the computer… vs.

return to recursion Composing functions into specific applications Creating general functions that will be useful everywhere (or almost…)

return to recursion Composing functions into specific applications Creating general functions that will be useful everywhere (or almost…) building blocks with which to compose…

sum, range def sum(L): """ input: a list of numbers, L output: L's sum """

sum, range def sum(L): """ input: a list of numbers, L output: L's sum """ if len(L) == 0: return 0.0 else: return L[0] + sum(L[1:]) Base Case if the input has no elements, its sum is zero Recursive Case if L does have an element, add that element's value to the sum of the REST of the list… This input to the recursive call must be "smaller" somehow…

sum, range def range(low,hi): """ input: two ints, low and hi output: int list from low up to hi """ excluding hi

sum, range def range(low,hi): """ input: two ints, low and hi output: int list from low up to hi """ if hi <= low: return [] else: return excluding hi

sum, range def range(low,hi): """ input: two ints, low and hi output: int list from low up to hi """ if hi <= low: return [] else: return [low] + range(low+1,hi) excluding hi

Recursion: Good News/Bad News Recursion is common (fundamental) in functional programming def dblList(L): """ Doubles all the values in a list. input: L, a list of numbers """ if L == []: return L else: return [L[0]*2] + dblList(L[1:]) But you can sometimes hide it away!

Map: The recursion "alternative" def dbl(x): return 2*x def sq(x): return x**2 def isana(x): return x=='a’ >>> map( dbl, [0,1,2,3,4,5] ) [0, 2, 4, 6, 8, 10] >>> map( sq, range(6) ) [0, 1, 4, 9, 16, 25] >>> map( isana, 'go away!' ) [0, 0, 0, 1, 0, 1, 0, 0] Hey… this looks a bit False to me! (1) map always returns a list (2) map(f,L) calls f on each item in L

Map ! def dblList(L): """ Doubles all the values in a list. input: L, a list of numbers """ if L == []: return L else: return [L[0]*2] + dblList(L[1:]) Without map def dbl(x): return x*2 def dblList(L): """ Doubles all the values in a list. input: L, a list of numbers """ return map(dbl, L) With map!

Map: a higher-order function In Python, functions can take other functions as input… def map( f, L ): Key Concep t Functions ARE data!

Why use map ?

Faster execution in Python – map optimized for operations in lists More elegant / shorter code, “functional in style” Avoid rewriting list recursion (build once, use lots)

Mapping without map : List Comprehensions >>> [ dbl(x) for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] >>> [ x**2 for x in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ c == 'a' for c in 'go away!' ] [0, 0, 0, 1, 0, 1, 0, 0] Anything you want to happen to each element of a list output input name that takes on the value of each element in turn the list (or string) any name is OK!

Mapping without map : List Comprehensions >>> [ dbl(x) for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] >>> [ x**2 for x in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ c == 'a' for c in 'go away!' ] [0, 0, 0, 1, 0, 1, 0, 0] def dbl(x): return 2*x def sq(x): return x**2 def isana(x): return x=='a’ >>> map( dbl, [0,1,2,3,4,5] ) [0, 2, 4, 6, 8, 10] >>> map( sq, range(6) ) [0, 1, 4, 9, 16, 25] >>> map( isana, 'go away!' ) [0, 0, 0, 1, 0, 1, 0, 0]

List Comprehensions def len(L): if L == []: return 0 else: return 1 + len(L[1:]) len(L) implemented via raw recursion sScore(s) sajak(s) def sajak(s): if len(s) == 0: return 0 else: if s[0] not in 'aeiou': return sajak(s[1:]) else: return 1+sajak(s[1:]) def sScore(s): if len(s) == 0: return 0 else: return letScore(s[0]) + \ sScore(s[1:]) scrabble score

List Comprehensions LC = [1 for x in L] return sum( LC ) len(L)

List Comprehensions LC = [1 for x in L] return sum( LC ) len(L) sajak(s) LC = [c in 'aeiou' for c in s] return sum( LC ) # of vowels

List Comprehensions LC = [1 for x in L] return sum( LC ) len(L) sScore(s) sajak(s) LC = [c in 'aeiou' for c in s] return sum( LC ) scrabble score # of vowels LC = [ letScore(c) for c in s] return sum( LC )

Write each of these functions concisely using list comprehensions… Write def count(e,L): Write def lotto(Y,W): input: e, any element L, any list or string output: the # of times L contains e example: count('f', 'fluff') == 3 input: Y and W, two lists of lottery numbers (ints) output: the # of matches between Y & W example: lotto([5,7,42,44],[3,5,7,44]) == 3 Y are your numbers W are the winning numbers Remember True == 1 and False == 0 Extra! Write def divs(N): input: N, an int >= 2 output: the number of positive divisors of N example: divs(12) == 6 (1,2,3,4,6,12)

LC = [x==e for x in L] return sum( LC ) count(e,L)

lotto(Y,W) LC = [c in Y for c in W] return sum( LC )

divs(N) LC = [ N%c==0 for c in range(1,N+1)] return sum( LC )

LC = [x==e for x in L] return sum( LC ) count(e,L) divs(N) lotto(Y,W) LC = [c in Y for c in W] return sum( LC ) LC = [ N%c==0 for c in range(1,N+1)] return sum( LC )