Computer Science 111 Fundamentals of Programming I

Slides:



Advertisements
Similar presentations
Fundamentals of Python: From First Programs Through Data Structures
Advertisements

Fundamentals of Python: From First Programs Through Data Structures
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
Computer Science 111 Fundamentals of Programming I Sequences: Lists.
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.
Lists in Python.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
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.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Computer Science 101 Introduction to Programming.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
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.
Computer Science 111 Fundamentals of Programming I Dictionaries redux.
Ch. 10 For Statement Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions.
Fundamentals of Python: First Programs Chapter 6: Design with Functions.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Arrays Chapter 7.
Fundamentals of Programming I Higher-Order Functions
Fundamentals of Programming I Overview of Programming
Chapter 11 - JavaScript: Arrays
CS314 – Section 5 Recitation 10
COMPSCI 107 Computer Science Fundamentals
Higher Order Functions
Fundamentals of Programming I Default and Optional Parameters
Advanced Python Idioms
Making Choices with if Statements
Fundamentals of Programming I Dictionaries redux
Fundamentals of Programming I Design with Functions
The Selection Structure
Fundamentals of Programming I Managing the Namespace
The Strategy Pattern II: Emulating Higher-Order Functions
JavaScript: Functions.
6.001 SICP Data abstractions
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 Number Systems
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Introduction to LINQ Chapter 11.
Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.
Object Oriented Programming in java
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
5. Functions Rocky K. C. Chang 30 October 2018
Python Functions Part I Presented by : Sharmin Abdullah
Python Primer 1: Types and Operators
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Value-Returning Functions: Generating Random Numbers
G. Pullaiah College of Engineering and Technology
Advanced Python Idioms
Topics Introduction to File Input and Output
Advanced Python Idioms
Terminal-Based Programs
COMPUTER PROGRAMMING SKILLS
Another Example Problem
Fundamentals of Python: First Programs Second Edition
General Computer Science for Engineers CISC 106 Lecture 03
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Chapter 5 JavaScript Numbers and Expressions
Presentation transcript:

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

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)

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

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]

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]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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?

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

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

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

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

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

Recursive Version of inputList

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

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

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

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

For Wednesday Finish Chapter 6