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

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Fundamentals of Python: From First Programs Through Data Structures Chapter 2 Software Development, Data Types, and Expressions.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Fundamentals of Python: From First Programs Through Data Structures
Computer Science 111 Fundamentals of Programming I Dictionaries.
Computer Science 111 Fundamentals of Programming I Files.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Introduction to Python
Fundamentals of Python: From First Programs Through Data Structures
Computer Science 111 Fundamentals of Programming I Sequences: Lists.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Fundamentals of Python: From First Programs Through Data Structures
Computer Science 209 The Strategy Pattern II: Emulating Higher-Order Functions.
Fundamentals of Python: First Programs
Computer Science 111 Fundamentals of Programming I Search Algorithms.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Lecture 16 – Open, read, write and close files.  At the end of this lecture, students should be able to:  understand file structure  open and close.
Fundamentals of Python: First Programs
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
CP104 Introduction to Programming Selection Structures_3 Lecture 11 __ 1 The Switch Statement The switch statement provides another means to select one.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
Input, Output, and Processing
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Computer Science 101 Introduction to Programming.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
Variables and Expressions CMSC 201 Chang (rev )
Property of Jack Wilson, Cerritos College1 CIS Computer Programming Logic Programming Concepts Overview prepared by Jack Wilson Cerritos College.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Variables When programming it is often necessary to store a value for use later on in the program. A variable is a label given to a location in memory.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Computer Science 111 Fundamentals of Programming I Dictionaries redux.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Ch. 10 For Statement Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
Higher Order Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Fundamentals of Python: First Programs Chapter 6: Design with Functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Fundamentals of Programming I Higher-Order Functions
Fundamentals of Programming I Overview of Programming
COMPSCI 107 Computer Science Fundamentals
Fundamentals of Programming I Default and Optional Parameters
Python’s input and output
Fundamentals of Programming I Dictionaries redux
Fundamentals of Programming I Design with Functions
Fundamentals of Programming I Managing the Namespace
Functions CIS 40 – Introduction to Programming in Python
CHAPTER FOUR Functions.
Topics Introduction to File Input and Output
Haskell Strings and Tuples
CISC101 Reminders Slides have changed from those posted last night…
Fundamentals of Programming I Files
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Computer Science 111 Fundamentals of Programming I
G. Pullaiah College of Engineering and Technology
Topics Introduction to File Input and Output
Python Basics with Jupyter Notebook
Terminal-Based Programs
COMPUTER PROGRAMMING SKILLS
Bryan Burlingame 17 April 2019
General Computer Science for Engineers CISC 106 Lecture 03
Topics Introduction to File Input and Output
More Basics of Python Common types of data we will work with
Presentation transcript:

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

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

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

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

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

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

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(, ) map A list A function oldlist = [2, 3, 4] newlist = list(map(math.sqrt, oldlist)) list Another list

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

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

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

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

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

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

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

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

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

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

For Wednesday Start Chapter 7