Higher Order Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

Week 5 while loops; logic; random numbers; tuples Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except.
Week 4 Strings, if/else, return, user input Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Week 4 gur zntvp jbeqf ner fdhrnzvfu bffvsentr Strings, if/else, return, user input Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Strings, if/else, return, user input
Week 7 Lists Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed.
Foldr CS 5010 Program Design Paradigms “Bootcamp” Lesson 5.4 TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: AAA © Mitchell.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
Python quick start guide
Computer Science 209 The Strategy Pattern II: Emulating Higher-Order Functions.
Unit 5 while loops; logic; random numbers; tuples Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.
Reynolds 2006 Complexity1 Complexity Analysis Algorithm: –A sequence of computations that operates on some set of inputs and produces a result in a finite.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Python Jim Eng Vote on class policy In lecture we discussed several ways in which you might show credits for content in the web pages.
Concurrent Algorithms. Summing the elements of an array
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions.
17 November 2015Birkbeck College1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
If/else, return, user input, strings
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Map, List, Stack, Queue, Set Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted,
Functional Programming in Python Abhishek Dasgupta Indian Institute of Science Education and Research, Kolkata.
PROGRAMMING: What’s It All About?
Higher Order Functions
Intro2CS Tirgul 11.
Intro to Programming Functional Programming
Python: Control Structures
Concurrent Algorithms
Logical Operators and While Loops
CHAPTER FOUR Functions.
Higher-Order Procedures
Week 4 gur zntvp jbeqf ner fdhrnzvfu bffvsentr
while loops; file I/O; introduction to lists
Concurrent Algorithms
MapReduce, Dictionaries, List Comprehensions
CS110: Discussion about Spark
CS190/295 Programming in Python for Life Sciences: Lecture 6
Week 7 Lists Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except where otherwise noted, this.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
while loops; logic; random numbers; tuples
Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.
Algorithm Discovery and Design
CSC1018F: Intermediate Python
(early slides assume map/filter)
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
Writing Functions( ) (Part 4)
Writing Functions( ) (Part 4)
Lambda Functions, MapReduce and List Comprehensions
CISC101 Reminders All assignments are now posted.
Introduction to Spark.
Logical Operators and While Loops
Concurrent Algorithms
Functions Functions being objects means functions can be passed into other functions: sort (list, key=str.upper)
Functional Programming
Concurrent Algorithms
Concurrent Algorithms
functions are also data! other functions as input!
Presentation transcript:

Higher Order Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under:

2 Functions as parameters Have you ever wanted to pass an entire function as a parameter Python has functions as first-class citizens, so you can do this You simply pass the functions by name

3 Higher-Order Functions A higher-order function is a function that takes another function as a parameter They are “higher-order” because it’s a function of a function Examples –Map –Reduce –Filter Lambda works great as a parameter to higher-order functions if you can deal with its limitations

4 Map map(function, iterable,...) Map applies function to each element of iterable and creates a list of the results You can optionally provide more iterables as parameters to map and it will place tuples in the result list Map returns an iterator which can be cast to list

5 Map Example Example nums = [0, 4, 7, 2, 1, 0, 9, 3, 5, 6, 8, 0, 3] nums = list(map(lambda x : x % 5, nums)) print(nums) #[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]

6 Map Problem Goal: given a list of three dimensional points in the form of tuples, create a new list consisting of the distances of each point from the origin Loop Method: - distance(x, y, z) = sqrt(x**2 + y**2 + z**2) - loop through the list and add results to a new list

7 Map Problem Solution from math import sqrt points = [(2, 1, 3), (5, 7, -3), (2, 4, 0), (9, 6, 8)] def distance(point) : x, y, z = point return sqrt(x**2 + y**2 + z**2) distances = list(map(distance, points))

8 Filter filter(function, iterable) The filter runs through each element of iterable (any iterable object such as a List or another collection) It applies function to each element of iterable If function returns True for that element then the element is put into a List This list is returned from filter in versions of python under 3 In python 3, filter returns an iterator which must be cast to type list with list()

9 Filter Example Example nums = [0, 4, 7, 2, 1, 0, 9, 3, 5, 6, 8, 0, 3] nums = list(filter(lambda x : x != 0, nums)) print(nums) #[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]

10 Filter Problem NaN = float("nan") scores = [[NaN, 12,.5, 78, math.pi], [2, 13,.5,.7, math.pi / 2], [2, NaN,.5, 78, math.pi], [2, 14,.5, 39, 1 - math.pi]] Goal: given a list of lists containing answers to an algebra exam, filter out those that did not submit a response for one of the questions, denoted by NaN

11 Filter Problem Solution NaN = float("nan") scores = [[NaN, 12,.5, 78, pi],[2, 13,.5,.7, pi / 2], [2,NaN,.5, 78, pi],[2, 14,.5, 39, 1 - pi]] #solution 1 - intuitive def has_NaN(answers) : for num in answers : if isnan(float(num)) : return False return True valid = list(filter(has_NaN, scores)) print(valid2) #Solution 2 – sick python solution valid = list(filter(lambda x : NaN not in x, scores)) print(valid)

12 Reduce reduce(function, iterable[,initializer]) Reduce will apply function to each element in iterable along with the sum so far and create a cumulative sum of the results function must take two parameters If initializer is provided, initializer will stand as the first argument in the sum Unfortunately in python 3 reduce() requires an import statement from functools import reduce

13 Reduce Example Example nums = [1, 2, 3, 4, 5, 6, 7, 8] nums = list(reduce(lambda x, y : (x, y), nums)) Print(nums) #(((((((1, 2), 3), 4), 5), 6), 7), 8)

14 Reduce Problem Goal: given a list of numbers I want to find the average of those numbers in a few lines using reduce() For Loop Method: - sum up every element of the list - divide the sum by the length of the list

15 Reduce Problem Solution nums = [92, 27, 63, 43, 88, 8, 38, 91, 47, 74, 18, 16, 29, 21, 60, 27, 62, 59, 86, 56] sum = reduce(lambda x, y : x + y, nums) / len(nums)

16 MapReduce A framework for processing huge datasets on certain kinds of distributable problems Map Step: - master node takes the input, chops it up into smaller sub-problems, and distributes those to worker nodes. - worker node may chop its work into yet small pieces and redistribute again

17 MapReduce Reduce Step: - master node then takes the answers to all the sub-problems and combines them in a way to get the output

18 MapReduce Problem: Given an how do you tell if it is spam? - Count occurrences of certain words. If they occur too frequently the is spam.

19 MapReduce map_reduce.py = ['the', 'this', 'annoy', 'the', 'the', 'annoy'] def in (x): if (x == "the"): return 1; else: return 0; map(in , l) #[1, 0, 0, 0, 1, 1, 0] reduce((lambda x, xs: x + xs), map(in , )) #3