Python Learning day 11th-functional programming

Source: Internet
Author: User
Tags define function

Before introducing functional programming, let's introduce a few conceptual things.

What is functional programming?

Features of functional programming:

1. Consider calculations as functions rather than directives;

2. Pure functional Programming: No variables required, no side effects, simple testing;

3. Support high-order functions, Code concise.

What is a higher order function?

Functions that can receive functions as arguments are called higher-order functions.

Features of higher order functions:

1. Variables can point to functions

2. Parameters of function can receive variables

3. One function can receive another function as a parameter

Functional programming supported by Python?

1. Not purely functional programming: allowed variables

2. Supports higher order functions: Functions can also be passed in as variables

3. Support closures: the ability to return functions with closures

4. Limited support for anonymous functions

The introduction of anonymous functions and closures, which are described in the following sections, are not described in detail here.

Higher order function-the function as a parameter
def fn (x,y,f): ...      return f (x) +f (y) ... Import Math>>> fn (4,16, math.sqrt)6.0
Python built-in several common high-order functions

Map (): Receives a function f and a list object, function f acts on each element of the list object, and returns a new list object.

def fn (x): ...      return x*x; Print map (fn,range (1,11)) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Reduce (): is also the receive function f and a list object, but the receive function F must pass in two parameters, and then call function f repeatedly for each element in Lsit and return the final result value.

def prod (x, y): ...      return x*y ... print reduce (prod,range (1,6))120//1 *2*3*4*5

Filter (): Receive function f and a list object, function f is to determine the elements of each list object, return True and false. Filter () Automatically filters out non-conforming elements based on the result of the decision and returns a new list of eligible elements.

def is_even_number (x): ...      return x%2==0 ... >>> Filter (Is_even_number,range (1,11)) [2, 4, 6, 8, 10]

As explained above for higher-order functions, you should understand that functions can be used as parameters, so since functions can do arguments, they can also return functions.

return function
>>>deff (): ...Print 'Call f () ....'...     //define function g: ...defg (): ...Print 'Call g () ....'//return function g: ...returng .....>>> x = f ()//calls F () call F () ....>>>x<function g at 0x7f62fab01c80>>>> x ()//calling X () is the code that executes the G () function definition call g () ....

For example: Write a function, receive a list, return a function, return a function to calculate the product of the parameter.

def fn (x, y): ...      return x*y; def Calc_prod (LST):      ... def My_calc ():          ... return reduce (fn,lst)      ... return My_calc ... >>> f = calc_prod (range (1,5))print  f ()24
Closed Package

The inner layer function refers to the variable of the outer function, and then returns the case of the inner layer function, called the closure.

Closure Features: The returned function refers to the local variables of the outer function. Therefore, to properly use closures, you can ensure that the referenced local variables cannot be changed after the function returns. To illustrate:

want to return 3 functions at a time, calculate 1x1,2x2,3x3def  count () separately     : ... = []...       for  in range (1,4): ...          def f (): ...               return i*i         ... Lst.append (f)      ... return LST ... >>> f1,f2,f3 = count ()>>> F1 ()9>>> f2 ()9>>> F3 (9)

The results are not the 1,4,9 we expected.

Lst.append (f), which simply saves each f () reference to the list, does not perform a calculation of I, so that after the last run of F (1), I has become 3.

Therefore, the return function does not refer to any loop variables, or to subsequent variables that change .

So how to rewrite the above code, get the desired 1,4,9. Value.

Method One:

def count (): ...      .. = []...       for  in range (1,4): ...           def f (): ...                return i*i           ... very different, F becomes f (), and this step has been i*i      ... return LST ... >>> f1,f2,f3 = count ()print  f1,f2,f31 4 9

Method Two:

def count (): ...      .. = []...       for  in range (1,4): ...           def F (m=i)://Incoming parameters                ... return m*m          ... Lst.append (f)      ... return LST ... >>> f1,f2,f3 = count ()print  F1 (), F2 (), F3 ()1 4 9

The problem arises because the function only obtains the outer parameter I when it is executed, and if I can be obtained when the function is defined, the problem can be solved. The default parameter is exactly the ability to get the I value when the definition is complete, and the function is run without parameter input, so the function f () definition is changed to f (M = i), the function f return value to m*m.

anonymous functions

The keyword lambda represents an anonymous function, and the x preceding the colon represents the function parameter.

The anonymous function has a limitation, that is, there can be only one expression, cannot write return, the return value directly writes the result of the expression.

Example one:

>>> map (Lambda x:x*x,range (1,5)) [1, 4, 9, 16]

Lambda X:x*x, can be seen as

def f (x): ...      return x*x

Example two:

Lambda if Else x>>> myabs ( -1)1>>> myabs (2)2

Lambda X:-x If x<0 else x can be seen as

def f (x): ...      =-x ...      if x<0:          ... return -x      ... Else :...          return X

Summary: This section focuses on Python's functional programming concepts and the definition and use of Python's higher-order functions.

Python Learning day 11th-functional programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.