Chapter 14 Advanced Function Topics CSC1310 Fall 2009.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Lecture 2 Introduction to C Programming
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Review for midterm exam Dilshad M. Shahid Spring NYU.
Chapter 2: Input, Processing, and Output
Introduction to Python
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
CHAPTER 6 FILE PROCESSING. 2 Introduction  The most convenient way to process involving large data sets is to store them into a file for later processing.
Fundamentals of Python: From First Programs Through Data Structures
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fundamentals of Python: First Programs
Chapter 2 Control. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Repetition, quick overview.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Chapter 1: A First Program Using C#. Programming Computer program – A set of instructions that tells a computer what to do – Also called software Software.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Built-in Data Structures in Python An Introduction.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Ch. 10 For Statement Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Python Functions.
Python 101 Dr. Bernard Chen University of Central Arkansas PyArkansas.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Python Let’s get started!.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Function Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Controlling Program Flow with Decision Structures.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Chapter 9: Value-Returning Functions
Python Let’s get started!.
Chapter 4: Making Decisions.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 4: Making Decisions.
Topics Introduction to Repetition Structures
Chapter 4: Making Decisions.
CHAPTER FOUR Functions.
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Programming Logic and Design Fourth Edition, Comprehensive
Topics Introduction to Repetition Structures
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
functions: argument, return value
The structure of programming
Topics Introduction to Repetition Structures
COMPUTER PROGRAMMING SKILLS
Introduction to Computer Science
Topics Introduction to File Input and Output
Presentation transcript:

Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Anonymous Function: lambda lambda lambda is an expression to generate a function. def Like def, it creates a function, but returns it instead of assigning it to the name. lambda arg1, arg2, … argN: expression lambda arg1, arg2, … argN: expression expression lambda is an expression not a statement. def  Can appear inside a list literal of function call (def can’t)  Returns a value (function) which can be assigned a name optionally.  def  def assigns new function to the name in the header. single expression lambda bodies are a single expression, not a block of statement.  Simply type the result as a naked expression  lambdadef  lambda is to code simple functions; def handles larger tasks

lambda Example >>>def func(x,y,z): return x+y+z >>>func(2,3,4) >>>f=lambda x,y,z : x+y+z >>>f(2,3,4) >>>x=(lambda a=‘e’,b=‘d’,c=‘t’:a+b+c) >>>x(‘hi’)

lambda Example >>>def knights(): title=‘Sir’ action=(lambda x: title+’ ’+x) return action >>>act=knights() >>>act(‘lancelot’) def The same scope rules as for def.

Jump Tables Jump tables Jump tables are lists or dictionaries of actions to be performed or demand. >>>L=[(lambda x:x**2),(lambda x: x**3)] >>>for f in L: print f(2) >>>print L[1](3) >>>key=‘cube’ >>>{‘add’: (lambda: 2+2), ‘square’: (lambda: 2*2), ‘cube’: (lambda: 2**3)}[key]() Multiway branching Multiway branching

List Comprehensions List comprehension expression List comprehension expression maps operations over sequences and collects results. ord() ord() returns the integer ASCII code of a character. chr() chr() returns the character for an ASCII code integer. >>>res=[] >>>for x in ‘string’:res.append(ord(x)) >>>res=map(ord,’string’) #apply func to seq >>>res=[ord(x) for x in ‘string’] #apply expr to seq List comprehensions List comprehensions collects the result of applying an arbitrary expression to a sequence of values, returns them in a new list.

Examples >>>[ x+2 for x in range(5)] >>>map( (lambda x: x+2),range(5)) List comprehensions can use if clause >>>res=[] >>>for x in range(7): if x%3==0: res.append(x) >>>[x for x in range(7) if x%3==0] >>>[x**2 for x in range(7) if x%3==0]

General Format [expression for target1 in sequence1[if condition] [expression for target1 in sequence1[if condition] for target2 in sequence2[if condition] for target2 in sequence2[if condition] …. …. for targetN in sequenceN[if condition]] for targetN in sequenceN[if condition]] >>>res=[] >>>for x in [1,2,3]: for y in [2,3,4]: res.append(x**y) >>>res=[x**y for x in [1,2,3] for y in [2,3,4]] >>>res=[x+y for x in ‘HI’ for y in ‘bye’] >>>res=[x+y for x in [1,2,3,4,5] if x%2==0 for y in [10,11,12] if y%3!=0]

for vs map() and List Comprehensions “Keep it simple”:for “Keep it simple”: for logic is more explicit map() for List comprehensions and map() are roughly two times faster than for map() List comprehensions and map() are expressions: they can be in places where for statements can’t like in the bodies of the lambda functions, within lists and dictionaries literals.

Generator Functions Generator Generator generates a sequence of values over time. Unlike a normal function Unlike a normal function, generator suspend and resume their execution and state around the point of value generation. As a result, it is useful alternative to compute an entire series of values up front. yield yield statement suspends the function and sends a value back to the caller, but retains state to allow the function to resume from where it left off.

Generator Examples >>>def squares(N): for i in range(N): yield i**2 >>>for k in squares(5): print k,’->’ >>>def squares1(N): res=[] for k in range(N): res.append(k**2) return res >>>for k in squares1(5): print k,’->’ >>>for k in [n**2 for n in range(5)] print k,’->’

Iterator iterator object interface Generator functions are compiled as generators; when called, they return a generator object that supports the iterator object interface. next Iterator objects define a next method which returns the next item in iteration or raises a special error to end the iteration. >>>x=squares(5) >>>x.next() iter() iter() produces iterator object for built-in datatypes. >>>D={‘a’:1,’b’:2,’c’:3} >>>x=iter(D) >>>x.next()

Function Design Concepts Cohesion Cohesion: how to decompose a task into functions  Each function should have a single, unified purpose.  Each function usually should be relatively small. Coupling Coupling: how functions should communicate  Use arguments for inputs and return for outputs. It is the best way to isolate external dependencies  Use global variables only when truly necessary.  Don’t change mutable arguments unless the caller expects it.