Download presentation
Presentation is loading. Please wait.
Published byNeil Hoover Modified over 7 years ago
1
Fundamentals of Programming I Higher-Order Functions
Computer Science 111 Fundamentals of Programming I Higher-Order Functions
2
Functions and Data In Python, functions are also first-class data objects Functions can be stored in data structures (lists, dictionaries, etc.) Functions can be passed as arguments to other functions and returned as the values of other functions
3
Example: Obtain a List of Integers
grades = inputIntegers("Enter a grade") scores = inputIntegers("Enter a score") weights = inputIntegers("Enter a weight") def inputIntegers(prompt): """Returns a list of input integers, using the string prompt.""" result = [] while True: data = input(prompt + " or return to quit: ") if data == "": break result.append(int(data)) return result
4
Example: Obtain a List of Inputs
names = inputList("Enter a name") ints = inputList("Enter an integer", int) floats = inputList("Enter a float", float) Inputs zero or more strings, using the prompt for each one Converts these strings using the type conversion function Returns a list of the results The default type conversion function is str
5
Example: Obtain a List of Inputs
names = inputList("Enter a name") ints = inputList("Enter an integer", int) floats = inputList("Enter a float", float) def inputList(prompt, convert = str): """Returns a list of input values, using the string prompt and the convert function.""" result = [] while True: data = input(prompt + " or return to quit: ") if data == "": break result.append(convert(data)) return result
6
Example: Analyzing Integers
file = open("numbers.txt", "r") words = file.read().split() integers = [] for word in words: integers.append(int(word)) maximum = max(integers) minimum = min(integers) average = sum(integers) / len(integers) Must transform a list of strings into a list of ints
7
Example: Analyzing Integers
file = open("numbers.txt", "r") words = file.read().split() integers = list(map(int, words)) maximum = max(integers) minimum = min(integers) average = sum(integers) / len(integers) map applies a function to a list of arguments and returns an iterator on the results map is a higher-order function, because it expects another function as an argument
8
Example: A List of Square Roots
oldlist = [2, 3, 4] newlist = [] for n in oldlist: newlist.append(math.sqrt(n)) # Do something with newlist
9
Example: A List of Square Roots
oldlist = [2, 3, 4] newlist = [] for n in oldlist: newlist.append(math.sqrt(n)) oldlist = [2, 3, 4] newlist = list(map(math.sqrt, oldlist)) Note that map does not return a list, but we can run list to get one from it
10
Syntax of map oldlist = [2, 3, 4]
newlist = list(map(math.sqrt, oldlist)) map(<a function>, <an iterable object>) A function An iterable object A list map list
11
Using map def cube(n): return n ** 3 oldlist = [2, 3, 4] newlist = list(map(cube, oldlist)) print(newlist) # Displays [8, 27, 64] Define the function to use in the mapping, and then map it onto a list
12
Using map How could we round to 1 place of precision?
oldlist = [2.17, 3.46, 4.54] newlist = list(map(round, oldlist)) print(newlist) # Displays [2, 3, 5] How could we round to 1 place of precision?
13
Using map oldlist = [2.17, 3.46, 4.54] newlist = list(map(round, oldlist, [1, 1, 1])) print(newlist) # Displays [2.2, 3.5, 4.5] The figures of precision for round are taken from the second list argument to map map(<a function of 2 args>, <list1>, <list2>)
14
Using map def roundto1place(n): return round(n, 1) oldlist = [2.17, 3.46, 4.54] newlist = list(map(roundto1place, oldlist)) print(newlist) # Displays [2.2, 3.5, 4.5] Alternatively, we could define a new function that expects one argument and rounds it to 1 place of precision
15
Using lambda for an Anonymous Function
oldlist = [2.17, 3.46, 4.54] newlist = list(map(lambda n: round(n, 1), oldlist)) print(newlist) # Displays [2.2, 3.5, 4.5] lambda creates a function βon the fly,β just for temporary use map(lambda <params>: <expression>, <a list of arguments>)
16
Simplifying changePerson
def changePerson(sentence): oldlist = sentence.split() newlist = [] for word in oldlist: newlist.append(replacements.get(word, word)) return " ".join(newlist) Builds a list of the results of applying the method get to the words in a list
17
Simplifying changePerson
def changePerson(sentence): oldlist = sentence.split() newlist = map(lambda word: replacements.get(word, word), oldlist) return " ".join(newlist) Builds a list of the results of applying the method get to the words in a list Note that join can work directly with the result of map, which need not be converted to a list
18
Simplifying changePerson
def changePerson(sentence): newlist = map(lambda word: replacements.get(word, word), sentence.split()) return " ".join(newlist) Much of data processing is simply transforming data structures into other data structures
19
Simplifying changePerson
def changePerson(sentence): return " ".join(map(lambda word: replacements.get(word, word), sentence.split())) Much of data processing is simply transforming collections of data values
20
Filters Sometimes we want to transform a list by removing elements that do not pass a test Such a transformation is called a filter A filter builds the list of elements that cause a Boolean function to return True
21
Example: A List of Even Numbers
oldlist = <get a list of numbers from somewhere> newlist = [] for n in oldlist: if n % 2 == 0: newlist.append(n) This type of operation is so common that Python includes a special function named filter to simplify it: oldlist = <get a list of numbers from somewhere> newlist = list(filter(lambda n: n % 2 == 0, oldlist)) A Boolean function A list Another list filter list
22
Example: A List of File Names
import os, os.path lyst = os.listdir(os.getcwd()) filelist = [] for name in lyst: if os.path.isfile(name): filelist.append(name) import os, os.path filelist = list(filter(os.path.isfile, os.listdir(os.getcwd()))) A Boolean function A list Another list filter list
23
Generalize in a New Function
import os, os.path def getNames(test, path): return list(filter(test, os.listdir(path))) filelist = getNames(os.path.isfile, os.getcwd()) dirlist = getNames(os.path.isdir, os.getcwd()) A Boolean function A list Another list filter list
24
Reducers Sometimes we want to use the contents of a list to compute a single value Such a transformation is called a reducer A reducer applies a function to pairs of elements to produce a value After each application, the value becomes an argument for the next application
25
Example: Products oldlist = <get a list of numbers from somewhere> total = 1 for n in oldlist: total *= n This type of operation is so common that Python includes a special function called reduce to simplify it: A list A function reduce oldlist = <get a list of numbers from somewhere> from functools import reduce product = reduce(lambda x, y: x * y, oldlist) A value
26
For Monday Start Chapter 7
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.