Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science 111 Fundamentals of Programming I

Similar presentations


Presentation on theme: "Computer Science 111 Fundamentals of Programming I"— Presentation transcript:

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

2 Arguments and Return Values
A function can receive data (arguments) from its caller A function can return a single value to its caller y = math.sqrt(x)

3 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 >>> math.sqrt(2) >>> math.sqrt(16) 4.0 >>>

4 Default and Optional Parameters
One or more parameters can have default values, so the caller can omit some arguments >>> round(3.1416) # Default precision is 0 3 >>> round(3.1416, 3) # Override the default 3.142 >>> list(range(5)) # Default lower bound is 0, and [0,1,2,3,4] # default step value is 1 >>> list(range(1, 5)) # Override the default lower bound [1,2,3,4] >>> list(range(1, 5, 2)) # Override lower bound and step [1,3]

5 Optional parameters can also be filled using keywords
Keyword Parameters Optional parameters can also be filled using keywords >>> lyst = [4, 2, 6, 3] # Items in random order >>> lyst.sort() # Default sort of list >>> lyst # Ascending order [2,3,4,6] >>> lyst = [4, 2, 6, 3] # Reset to original order >>> lyst.sort(reverse = True) # Override default sort order >>> lyst # Descending order [6,4,3,2]

6 Convert Based Numbers to ints
Write a general function that expects a string representation of a number and its base (an int) as arguments The function returns the integer represented >>> convert('10', 2) # 102 = 2 2 >>> convert('10', 10) # 1010 = 10 10 >>> convert('10', 16) # 1016 = 16 16 >>> convert('100', 2) # 1002 = 4 4

7 Implementation def convert(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] * base ** expo expo -= 1 return intValue

8 Default and Optional Parameters
One or more parameters can have default values, so the caller can omit some arguments >>> convert('111', 2) 7 >>> convert('111', 10) 111 >>> convert('111', 16) 273 >>> convert('111') # Same result as the previous line The caller can treat base16 as the standard base in this system or use other bases by mentioning them

9 Implementation def convert(digits, base = 16):
"""Returns the integer represented by the digits in the given base, with 16 as the default base.""" intValue = 0 expo = len(digits – 1) for ch in digits: ch = string.upper(ch) intvalue += hexdigits[ch] * base ** expo expo -= 1 return intValue

10 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 <function name>(<required args>, <optional args>): def <function name>(<required params>, <default params>):

11 Some Syntax Rules A required parameter is just a name
A default parameter looks like an assignment statement def <function name>(<name>,…, <name> = <expression>,…):

12 Ways to Call a Function def convert(digits, base = 16): >>> convert('111') 273 >>> convert('111', 16) >>> convert('111', base = 16) 273 >>> convert(digits = '111', base = 16) >>> convert(base = 16, digits = '111') Order is important, unless you use all the keywords

13 Processing Lists listOfStrings = [] for number in listOfNumbers: listOfStrings.append(str(number)) listOfAbsolutes = [] for number in listOfNumbers: listOfAbsolutes.append(abs(number)) listOfRoots = [] for number in listOfNumbers: listOfRoots.append(math.sqrt(number)) Each pattern applies a function to each value in a list to produce a list of results

14 Generalize to a Map def map(aFunction, listOfArgs): listOfResults = [] for item in listOfArgs: listOfResults.append(aFunction(item)) return listOfResults Each pattern applies a function to each value in a list to produce a list of results

15 The map function listOfStrings = list(map(str, listOfNumbers)) listOfAbsolutes = list(map(abs, listOfNumbers)) listOfRoots = list(map(math.sqrt, listOfNumbers)) map takes a function and a list as arguments, and returns an iterable object on the results Then run list to build a list from this object

16 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

17 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

18 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

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

20 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

21 Syntax of map oldlist = [2, 3, 4]
newlist = list(map(math.sqrt, oldlist)) map(<a function>, <a list of arguments>) A function A list Another list map list

22 Using map to Simplify Code
fileName = input("Enter the file name: ") inputFile = open(fileName, "r") numberList = [] for word in inputFile: numberList.append(int(word)) 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.")

23 Using map to Simplify Code
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.")

24 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

25 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?

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

27 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

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

29 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

30 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

31 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

32 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

33 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.""" results = [] while True: data = input(prompt + " or return to quit: ") if data == "": return results results.append(convert(data))

34 Recursive Version of inputList

35 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

36 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

37 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

38 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

39 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

40 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

41 For Wednesday Finish Chapter 6


Download ppt "Computer Science 111 Fundamentals of Programming I"

Similar presentations


Ads by Google