Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 14 Advanced Function Topics CSC1310 Fall 2009.

Similar presentations


Presentation on theme: "Chapter 14 Advanced Function Topics CSC1310 Fall 2009."— Presentation transcript:

1 Chapter 14 Advanced Function Topics CSC1310 Fall 2009

2 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

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

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

5 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

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

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

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

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

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

11 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,’->’

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

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


Download ppt "Chapter 14 Advanced Function Topics CSC1310 Fall 2009."

Similar presentations


Ads by Google