computer science 111 fundamentals of programming i default and optional parameters higher-order...
TRANSCRIPT
![Page 1: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/1.jpg)
Computer Science 111
Fundamentals of Programming I
Default and Optional Parameters
Higher-Order Functions
![Page 2: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/2.jpg)
Why Use Parameters?
• Parameters allow a function to be used with different data in different parts of a program
• The general method or algorithm is the same, but the arguments vary with the situation
>>> repToInt('10', 2)2>>> repToInt('10', 10)10>>> repToInt('10', 16)16
![Page 3: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/3.jpg)
Implementationdef repToInt(digits, base): """Returns the integer represented by the digits in the given base.""" intValue = 0 expo = len(digits – 1) for ch in digits: ch = string.upper(ch) intvalue += hexdigits[ch] ** expo expo -= 1 return intValue
![Page 4: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/4.jpg)
Default and Optional ParametersOne or more parameters can have default values, so the caller can omit some arguments
>>> repToInt('111', 2)7>>> repToInt('111', 10)111>>> repToInt('111', 16)273>>> repToInt('111') # Same result as the previous line273
The caller can treat base16 as the standard base in this system or use other bases by mentioning them
![Page 5: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/5.jpg)
Default Parameters
def repToInt(digits, base = 16): # Code that uses digits and base as before
…>>> repToInt('111', 16)273>>> repToInt('111') # Same result as the previous line273
The caller must still pass an argument for digits, but the argument for base is now optional
One or more parameters can have default values, so the caller can omit some arguments
![Page 6: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/6.jpg)
Some Syntax Rules
• The required arguments used in a function call must match the required parameters named in the definition, by position
• The programmer should list the required parameters first (to the left) in the function’s definition
def <function name>(<required params>, <default params>):
![Page 7: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/7.jpg)
Some Syntax Rules
• A required parameter is just a name
• A default parameter looks like an assignment statement
def <function name>(<name>,…, <name> = <expression>,…):
![Page 8: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/8.jpg)
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
![Page 9: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/9.jpg)
Higher-Order Functions
• A higher-order function can receive another function as an argument
• The higher-order function then applies the argument function in some manner
• HOFs are a powerful way of simplifying code
![Page 10: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/10.jpg)
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 == "": return result result.append(convert(data)) return result
![Page 11: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/11.jpg)
Mappers
• Sometimes we want to transform a list of data into a list of results
• Such a transformation is called a mapping
• Build and return a list that contains the results of applying a function to each of the elements in another list
![Page 12: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/12.jpg)
Example: A List of Square Roots
oldlist = [2, 3, 4]
newlist = []
for n in oldlist: newlist.append(math.sqrt(n))
# Do something with newlist
![Page 13: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/13.jpg)
Example: A List of Square Roots
oldlist = [2, 3, 4]
newlist = []
for n in oldlist: newlist.append(math.sqrt(n))
This type of operation is so common that Python includes a special function called map to simplify it:
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
![Page 14: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/14.jpg)
Syntax of map
map(<a function>, <a list of arguments>)
mapA list
A function
oldlist = [2, 3, 4]
newlist = list(map(math.sqrt, oldlist))
listAnother list
![Page 15: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/15.jpg)
Using mapfileName = input("Enter the file name: ")inputFile = open(fileName, "r")
numberList = list(map(int, inputFile.read().split()))
if len(numberList) > 0: print("The number of numbers is", len(numberList)) print("The sum total is", sum(numberList)) print("The average is", sum(numberList) / len(numberList) print("The maximum is", max(numberList)) print("The minimum is", min(numberList))else: print("The file is empty.")
![Page 16: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/16.jpg)
Using map
Define the function to use in the mapping, and then map it onto a list
def cube(n): return n ** 3
oldlist = [2, 3, 4]
newlist = list(map(cube, oldlist))
print(newlist) # Displays [8, 27, 64]
![Page 17: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/17.jpg)
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]
![Page 18: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/18.jpg)
Using map
The figures of precision for round are taken from the second list argument to 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]
map(<a function of 2 args>, <list1>, <list2>)
![Page 19: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/19.jpg)
Using map
Alternatively, we could define a new function that expects one argument and rounds it to 1 place of precision
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]
![Page 20: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/20.jpg)
Using lambda for an Anonymous Function
map(lambda <params>: <expression>, <a list of arguments>)
lambda creates a function “on the fly,” just for temporary use
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]
![Page 21: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/21.jpg)
Simplifying changePersondef 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
![Page 22: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/22.jpg)
Simplifying changePersondef 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
![Page 23: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/23.jpg)
Simplifying changePersondef 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
![Page 24: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/24.jpg)
Simplifying changePersondef changePerson(sentence): return " ".join(map(lambda word: replacements.get(word, word), sentence.split()))
Much of data processing is simply transforming collections of data values
![Page 25: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/25.jpg)
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
![Page 26: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/26.jpg)
Example: A List of Even Numbersoldlist = <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))
filterA list Another list
A Boolean function
list
![Page 27: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/27.jpg)
Example: A List of File Namesimport 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())))
filterA list Another list
A Boolean function
list
![Page 28: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/28.jpg)
Generalize in a New Functionimport 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())
filterA list Another list
A Boolean function
list
![Page 29: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/29.jpg)
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
![Page 30: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/30.jpg)
Example: Products
oldlist = <get a list of numbers from somewhere> total = 1for n in oldlist: total *= n
This type of operation is so common that Python includes a special function called reduce to simplify it:
oldlist = <get a list of numbers from somewhere>
from functools import reduce
product = reduce(lambda x, y: x * y, oldlist)
reduce
A list
A value
A function
![Page 31: Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions](https://reader034.vdocuments.net/reader034/viewer/2022052308/5697bfc71a28abf838ca7bb8/html5/thumbnails/31.jpg)
For Wednesday
Start Chapter 7