Python Learning notes (v)

Source: Internet
Author: User
Tags abs for in range

Directory:

I. Higher-order functions

Two. return function

Three. Anonymous functions

Four. Partial function

I. Higher-order functions

Higher-order functions are called Higher-order function in English.

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

A simple high-order function:

 

def Add (x, Y, f):     return f (x) + f (Y)

When we call Add ( -5,6,abs), the parameters x,y,f, respectively, receive -5,6,abs.

Map/reduce

Python has the map () and reduce () functions built into it.

Map

The map () function receives two parameters, one is the function, and the other is iterable,map the incoming function to each element of the sequence and returns the result as a new iterator.

Example: For example, we have a function f (x) = x2, in order to function on a list[1,2,3,4,5,6,7,8,9], you can use map to implement.

>>>def  F (x): ...         return x*x ... >>>r = Map (f, [1,2,3,4,5,6,7,8,9])>>>list (R) [1, 4, 16, 25, 36, 49, 64, 81]

The parameter that the map passes in is F, which is the function object itself. Since the result r is one Iterator , it is an Iterator inert sequence, so the list() function allows it to calculate the entire sequence and return a list.

Reduce

Reduce functions a function in a sequence [x1,x2,x3,x4 ...] , the function must accept two parameters, and reduce accumulates the result and the next element of the sequence, the effect is:

Reduce (f, [X1, x2, X3, x4]) = f (f (x1, x2), x3), x4)

For example, to sum a sequence, you can use it to reduce implement

 from Import Reduce def Add (x, y): ...      return x + y ... >>> reduce (add, [1, 3, 5, 7, 9])25

Of course, the sum operation can be directly built into Python functions sum() , no need to use reduce .

But if you want to [1, 3, 5, 7, 9] transform the sequence into integers 13579 , you can put reduce it in handy:

 from Import Reduce def fn (x, y): ...      return x * ten + y ... >>> reduce (FN, [1, 3, 5, 7, 9])13579

This example is not very useful in itself, but if we consider that the string str is also a sequence, with a slight change to the above example, map() we can write the str converted int function:

>>> fromFunctoolsImportReduce>>>deffn (x, y): ...returnX * 10 +y ...>>>defChar2num (s): ... digits= {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}...     returnDigits[s] ...>>> reduce (FN, map (Char2num,'13579'))13579

str2intthe function that is organized into one is:

 fromFunctoolsImportreducedigits= {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}defStr2Int (s):deffn (x, y):returnX * 10 +ydefChar2num (s):returnDigits[s]returnReduce (FN, map (Char2num, s))

You can also use lambda functions to further simplify:

 fromFunctoolsImportreducedigits= {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}defChar2num (s):returnDigits[s]defStr2Int (s):returnReduceLambdaX, y:x * + y, map (Char2num, s))

Filter

Python's built-in filter () function is used for filtering sequences. Like map (), filter () also accepts a function and a sequence. Unlike map (), filter () applies the incoming element to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.

For example: In a list, delete an even number, leaving only the odd number:

def is_odd (n):     return n%2 = = 1list (filter (is_odd, [1,2,4,5,6,9,10,15]))

Notice that the filter () function returns a iterator, which is an inert sequence, so to force filter () to complete the result of the calculation, you need to use the list () function to get all the results and return to the list.

To calculate a prime number with a filter:

One method of calculating primes is the filter method, which has the following algorithm:

First, list 2 all the natural numbers from the beginning, constructing a sequence:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

To take the first number of a sequence 2 , it must be a prime, and then 2 sift away the multiples of the sequence 2 :

3, 4, 5, 6, 7, 8, 9,, one, ten,, 18 , ...

To take the first number of a new sequence 3 , it must be a prime, and then 3 sift away the multiples of the sequence 3 :

5, 6, 7, 8, 9, Ten, one, A, a, a, (+), +, ...

Take the first number of a new sequence 5 , and then sift away the multiples of the 5 sequence 5 :

7, 8, 9, Ten, one, A, and a , 2>18, ...

Keep sifting down and you can get all the primes.

Using Python to implement this algorithm, you can first construct an 3 odd sequence from the beginning:

def _odd_iter ():      = 1 while      True:        = n+2        yield n

Note that this is a generator and is a wireless sequence.

Then define a filter function:

def _not_divisible (n):     return Lambda x:x%n >0

Finally, define a generator that continually returns the next prime number:

def primes ():     yield 2    #  initial sequence while      True:         #  Returns the first number of a sequence        yield  n        #  constructs a new sequence

The generator returns the first prime number 2 , and then takes advantage of the filter() new sequence that continuously produces the filter.

Because primes() it is also an infinite sequence, it is called to set a condition for exiting the loop:

 for inch primes ():     if n <:        print(n)    Else:        break 

Sorted

Sorting algorithms

The python built-in sorted () function allows you to sort the list:

>>>sorted ([5, -12, 9, -21]) [-21,-12, 5, 9, 36]
>>>sorted ([5, -12, 9, -21], key=ABS) [5, 9,-12,-21, 36]

Two. return function

function as return value

To implement the summation of a mutable parameter:

def lazy_sum (*args):    def  sum ():        = 0        for in  args:            = ax + n        return  ax    return sum

When we call Lazy_sum (), we return the SUM function instead of summing the result:

>>>f = Lazy_sum (1, 3, 5, 7, 9)>>>F<function lazy_sum.<locals>.sum at 0x101c6ed90>

The result of summing is actually computed when the function f is called:

>>>F ()25

In this example, we define the function sum in the function lazy_sum, and the inner function sum can refer to the arguments and local variables of the external function lazy_sum, and when Lazy_sum returns the function sum, the relevant parameters and variables are stored in the returned function, which is called "closures" The program structure has great power.

Note again that when we call lazy_sum() , each call returns a new function, even if the same parameter is passed in:

>>> f1 = lazy_sum (1, 3, 5, 7, 9)>>> F2 = lazy_sum (1, 3, 5, 7, 9)>>> f1==F 2False

The invocation results of F1 () and F2 () do not affect each other.

Closed Package

Notice that the returned function references the local variable args within its definition, so when a function returns a function, its internal local variables are referenced by the new function.

Another problem to be aware of is that the returned function is not executed immediately, but not until F () is called.

def count ():     = []    for in range (1,4):        def  F ():             return i*i        fs.append (f)    return= count ()

In the example above, each loop creates a new function and then returns the 3 functions that were created.

You might think that calling F1 (), F2 (), F3 () results should be 1,4,9, but the actual result is:

>>> F1 ()9>>> F2 () 9>>> f3 ()9

All of them 9 ! The reason is that the returned function refers to the variable i , but it is not executed immediately. When all 3 functions are returned, the variables they refer to are i already turned 3 , so the end result is 9 .

One thing to keep in mind when returning closures: The return function does not refer to any loop variables, or to subsequent variables that change.

What if you must refer to a loop variable? The method is to create a function that binds the current value of the loop variable with the parameter of the function, regardless of how the loop variable is subsequently changed, and the value that is bound to the function parameter remains the same:

def count ():     def F (j):         def g ():             return j*J        return  g    = []    for  in range (1, 4):        #  F (i) is executed immediately, so the current value of I is passed in F ()    return FS

Three. Anonymous functions

Cases:

>>>list (Map (Lambda x:x*x, [1,2,3,4,5,6])) [1,4,9,16,25,36]

The anonymous function lambda x:x*x is actually:

def f (x):

Return x*x

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

There is a limit to the anonymous function, that is, there can be only one expression, without writing return, the return value is the result of that expression.

There is a benefit to using anonymous functions because the function does not have a name and does not have to worry about function name collisions. In addition, the anonymous function is also a function object, you can assign the anonymous function to a variable, and then use the variable to invoke the function:

Lambda x:x * x>>> F<function <lambda> at 0x101c6ef28>> >> F (5)25

Similarly, anonymous functions can be returned as return values, such as:

def build (x, y):     return Lambda: x * x + y * y

Four. Partial function

Python's Functools module provides a number of useful functions, one of which is the partial function.

>>>Import  functools>>>int2 = functools.partial (int, base=2)>> >int2 ('1000000')64

So, the simple summary functools.partial of the function is to put some parameters of a function fixed (that is, set the default), return a new function, call this new function is more simple.

Python Learning notes (v)

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.