Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions."— Presentation transcript:

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

2 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

3 Implementation def 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

4 Default and Optional Parameters One 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 line 273 The caller can treat base 16 as the standard base in this system or use other bases by mentioning them

5 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 line 273 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

6 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 (, ):

7 Some Syntax Rules A required parameter is just a name A default parameter looks like an assignment statement def (,…, =,…):

8 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

9 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

10 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

11 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

12 Example: A List of Square Roots oldlist = [2, 3, 4] newlist = [] for n in oldlist: newlist.append(math.sqrt(n)) # Do something with newlist

13 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

14 Syntax of map map(, ) map A list A function oldlist = [2, 3, 4] newlist = list(map(math.sqrt, oldlist)) list Another list

15 Using map fileName = 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.")

16 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]

17 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]

18 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(,, )

19 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]

20 Using lambda for an Anonymous Function map(lambda :, ) 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]

21 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

22 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

23 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

24 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

25 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

26 Example: A List of Even Numbers oldlist = 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 = newlist = list(filter(lambda n: n % 2 == 0, oldlist)) filter A listAnother list A Boolean function list

27 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()))) filter A listAnother list A Boolean function list

28 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()) filter A listAnother list A Boolean function list

29 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

30 Example: Products oldlist = 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: oldlist = from functools import reduce product = reduce(lambda x, y: x * y, oldlist) reduce A list A value A function

31 For Wednesday Start Chapter 7


Download ppt "Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions."

Similar presentations


Ads by Google