13
Chapter 14 Chapter 14 Advanced Function Advanced Function Topics Topics CSC1310 Fall 2009 CSC1310 Fall 2009

Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Embed Size (px)

Citation preview

Page 1: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Chapter 14 Chapter 14 Advanced Function Advanced Function TopicsTopics

CSC1310 Fall 2009CSC1310 Fall 2009

Page 2: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Anonymous Function: Anonymous Function: lambdalambda lambdalambda is an expression to generate a function. Like defdef, it creates a function, but returns it instead of

assigning it to the name. lambda arg1, arg2, … argN: expressionlambda arg1, arg2, … argN: expression lambda is an expressionexpression not a statement.

Can appear inside a list literal of function call (defdef can’t) Returns a value (function) which can be assigned a name

optionally. defdef assigns new function to the name in the header.

lambda bodies are a single expressionsingle expression, not a block of statement. Simply type the result as a naked expression lambdalambda is to code simple functions; defdef handles larger tasks

Page 3: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

lambda Examplelambda 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’)

Page 4: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

lambda Examplelambda Example

>>>def knights():

title=‘Sir’

action=(lambda x: title+’ ’+x)

return action

>>>act=knights()

>>>act(‘lancelot’) The same scope rules as for defdef.

Page 5: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Jump TablesJump Tables Jump tablesJump 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 branchingMultiway branching

Page 6: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

List ComprehensionsList Comprehensions List comprehension expressionList 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 comprehensionsList comprehensions collects the result of applying an

arbitrary expression to a sequence of values, returns them in a new list.

Page 7: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

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

Page 8: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

General FormatGeneral 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]

Page 9: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

for vs map() and List for vs map() and List ComprehensionsComprehensions ““Keep it simple”:Keep it simple”: forfor logic is more explicit List comprehensions and map()map() are roughly two

times faster than forfor List comprehensions and map()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.

Page 10: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Generator FunctionsGenerator Functions GeneratorGenerator generates a sequence of values over

time. Unlike a normal functionUnlike 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.

Page 11: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Generator ExamplesGenerator 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,’->’

Page 12: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

IteratorIterator Generator functions are compiled as generators; when called, they

return a generator object that supports the iterator object iterator object interfaceinterface.

Iterator objects define a nextnext method which returns the next item in iteration or raises a special error to end the iteration.

>>>x=squares(5)

>>>x.next()

>>>x.next() iter()iter() produces iterator object for built-in datatypes.

>>>D={‘a’:1,’b’:2,’c’:3}

>>>x=iter(D)

>>>x.next()

Page 13: Chapter 14 Advanced Function Topics CSC1310 Fall 2009

Function Design ConceptsFunction Design Concepts CohesionCohesion: how to decompose a task into functions

Each function should have a single, unified purpose. Each function usually should be relatively small.

CouplingCoupling: 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.