Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order...

Preview:

Citation preview

Computer Science 111

Fundamentals of Programming I

Default and Optional Parameters

Higher-Order Functions

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

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

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

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

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>):

Some Syntax Rules

• A required parameter is just a name

• A default parameter looks like an assignment statement

def <function name>(<name>,…, <name> = <expression>,…):

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

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

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

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

Example: A List of Square Roots

oldlist = [2, 3, 4]

newlist = []

for n in oldlist: newlist.append(math.sqrt(n))

# Do something with newlist

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

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

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.")

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]

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]

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>)

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]

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]

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

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

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

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

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

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

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

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

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

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

For Wednesday

Start Chapter 7

Recommended