Python: Advanced Features of functions

Source: Internet
Author: User
Tags abs closure sorts square root

In many languages, the function itself is allowed to be passed as a parameter to other parameters: the so-called higher order function. There are similar features in Python:

First, map/reduce, filter, sorted

The idea of map-reduce in Hadoop has become a built-in function in Python. A map is a function that is used for each element in the list. Reduce then takes the first 2 elements from the list to the specified function, and then repeats the result with the remaining elements until the list is processed.1.1Map Example: (*10 all elements in list)
def fn_map (x):    print ("fn_map->", x)    return * XL = [3, 4, 6, 8]print (list (map (Fn_map, L))) print ("\ n")

Output:

fn_map-> 3fn_map-> 4fn_map-> 6fn_map-> 8[30, 40, 60, 80]

In conjunction with map, we then add the Reduce function (the final effect: *10 all the elements to the square and finally the square root of the "squared sum")

def fn_sqrt (x, y):    print ("fn_sqrt->", X, ",", y)    return math.sqrt (x * * 2 + y * * 2) def fn_map (x):    print ("Fn_ Map-> ", x)    return * XL = [3, 4, 6, 8]result = reduce (fn_sqrt, map (Fn_map, L)) print (" \ n ") print (math. SQRT ((3 * 10) * * 2 + (4 * 10) * * 2 + (6 * 10) * * 2 + (8 * 10) * * 2))

Note: To import math First, the above code output is as follows:

Fn_map-> 3fn_map-> 4fn_sqrt->, 40fn_map-> 6fn_sqrt-> 50.0, 60fn_map-> 8fn_sqrt-> 78.10249675906 654, 80111.80339887498948111.80339887498948

The above example, may not be practical, the following is a more practical example, the first letter of each word capitalized, the other letters lowercase.

def normalize (name):    return Name[:1].upper () + name[1:].lower () L1 = [' Adam ', ' LISA ', ' BarT ']print (list (map) Normalize, L1)))

Output:

[' Adam ', ' Lisa ', ' Bart ']

1.2 Filter

Filter is similar to the filter of stream in Java8, it can be implemented to filter the elements in the collection according to some rules.

Example 1: Find an even number within 10

result = Filter (lambda x:x% 2 = = 0, range (1, one)) print (list result) # The above notation is equivalent to this def even (x):    return x% 2 = = 0pri NT (List (filter (even, range (1, 11)))

Output:

[2, 4, 6, 8, 10] [2, 4, 6, 8, 10]

Example 2: Find the number of "returns" within 200 (i.e.: left-to-right, right-to-left, all the same numbers, for example: 131, 141)

def is_palindrome1 (n):    if n <:        return True    s = str (n)    for I in range (0, int (len (s)/2)):        if S[i ] = = S[-i-1]:            return True    return falsedef is_palindrome2 (n):    s1 = str (n)    s2 = list (Reversed (S1))    re Turn list (S1) = = S2print (list (filter (is_palindrome1, Range (1, 201))) Print (List (filter (is_palindrome2, Range (1, 201)) ))

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191] [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]

  

1.3 Sorted

Python's built-in sort function, sorted, supports the sorting of numbers/letters/and complex objects by default from small to large, and the collation of complex objects can be customized by developers. Refer to the following example:

Origin = [-1, 3,-5, 2,-4, 6]# from small to large sort a = sorted (origin) print (a) # by ABS Absolute, from small to sort a = sorted (origin, Key=abs) print (a) # from big to small rows Order a = sorted (origin, Reverse=true) print (a) origin = ["Xy", "AA", "Bb", "DD", "CC", "AA", "Zo"]# by letter ASCII value from small to large sort print (sorted ( Origin) # Sorts the values after the letters are capitalized (i.e. ignoring the case) print (sorted (origin, Key=str.upper)) # Sorts the values after the letters to uppercase print (sorted (Origin, Key=str.upper (reverse=true)) # Complex objects sorted by origin = [(' Bob ', '), (' Adam ', "the"), (' Bart ', "the"), (' Lisa ', "]def") By_name (t):    return t[0]# Press Name sort print (sorted (origin, Key=by_name)) def by_score (t):    return t[1]# row by score print (sorted (origin, Key=by_score, Reverse=true))

Output:

[-5,-4,-1, 2, 3, 6] [-1, 2, 3,-4,-5, 6] [6, 3, 2,-1,-4,-5] [' AA ', ' Bb ', ' Xy ', ' Zo ', ' AA ', ' CC ', ' DD '] [' AA ', ' AA ', ' Bb ', ' CC ', ' dd ', ' Xy ', ' Zo '] [' Zo ', ' Xy ', ' dd ', ' CC ', ' Bb ', ' AA ', ' AA '] [(' Adam ', the "," (' Bart '), (' Bob ', '), (' Lisa ', 88)] [(' Adam ', "the"), (' Lisa ', ","), (' Bob ', '), (' Bart ', 66)]

Second, delay calculation/closure

Python's function definitions can be nested (i.e., functions that define functions inside the function), and this feature makes it easy to implement lazy computations :

Import Timedef export1 (month):    print ("Export1 month:", month, "doing ...")    Time.sleep (5)    print ("Export1 done! ") def export2 (month):    def do ():        print ("Export2 month:", month, "doing ...")        Time.sleep (5)        print (" Export2 done! ")    return doexport1 print ("----------------") r2 = Export2 () print (R2) R2 ()

Here we simulate a time-consuming export function (assuming that the incoming month is required and then export the report data for that month), Export1 is the regular version, and the call to Export1 is executed immediately. Instead, EXPORT2 returns an intrinsic function do (), returns a function after calling Export2, and does not actually execute (which can be understood as returning a business processing algorithm rather than processing the result), and then invoking the return function when the result is really needed.

The above code output is as follows:

Export1 month:10  doing...export1 done!----------------<function export2.<locals>.do at 0x107a24a60> Export2 month:10  Doing...export2 done!

  

Closed Package

Many languages support the closure feature, which is certainly true in Python, as shown in the following example:

def my_sqrt1 (n):    r = []    def do ():        for I in range (1, n + 1):            r.append (i * * 2)        return r    return DOA = My_sqrt1 (4) Print (type (a)) B = A () print (type (b)) print (b)

Output:

<class ' function ' ><class ' list ' >[1, 4, 9, 16]

Closures have a classic pit: do not use "variables with variable values" (e.g., variables in the For loop) in a closure function. The reason is that the closure in Python is essentially an "intrinsic" delay calculation, and if there is a loop variable, the closure function does not execute during the loop, and so the loop ends, and the loop variable referenced in the closure is actually the end value after the loop. A bit of a detour, look at the following example:

def my_sqrt2 (n):    r = []    for I in range (1, n + 1):        def do ():            r.append (i * * 2)            return r    return DOA = My_sqrt2 (4) Print (type (a)) B = A () print (type (b)) print (b)

Output:

<class ' function ' ><class ' list ' >[16]

Explain: when calling a = My_sqrt2 (4), My_sqrt2 (4) executes immediately, when the Fox Loop executes, the value of the last I stops at 4, and the value is closed in the Do function, and is not executed immediately. And then call a (), this is the time to actually call the Do () function, when I value = 4, so the final r[] list, only a value is recovered 4*4=16

If you want to use the loop variable, you can only want to call this loop variable, also closed to an internal function, and then use, such as the following:

def my_sqrt3 (n):    def F (j):        def g ():            return J * * 2        return g    r = [] for    I in range (1, n + 1):        R. Append (f (i))    return RA = my_sqrt3 (4) Print (type (a)) for x in a:    print (x ())

This example is very interesting to study, R.append (f (i)), the list is not the result of the calculation, but the function G returned in F (j), so a = My_sqrt3 (4) Here, a get a function of a list, Then every instance of the G function in the list closes the variable I of the secondary loop, because of the closure, the I value has been sealed inside G, no matter how the external for loop variable, does not affect the function G.

The output is as follows:

<class ' list ' >14916

Finally, to see a teacher Liao tutorial on the closure of the problem, the closure of the wording of the writing a counter:

Def create_counter1 ():    r = [0]    def counter ():        r[0] + = 1        return r[0]    return countercount = Create _counter1 ();p rint ([count (), count (), count ()])

Output:

[1, 2, 3]

For a neat and tidy programmer, you might find it a bit wasteful to set up a list that only holds 1 elements. You can change the wording:

Def create_counter2 ():    n = 0    def counter ():        nonlocal n        n + = 1        return n    return countercount = Crea Te_counter2 ();p rint ([count (), count (), count ()])

Output:

[1, 2, 3]

Note Here is a keyword nonlocal, called the New keyword introduced by Python3, in order to let inside of the closure function, can read and write the variables outside the internal function. (But in the 1th notation, r=[0] is not defined externally, either? The difference is that the list is a complex variable type, and the 2nd is a simple type of variable, as a Python beginner, not very understanding of this philosophical thought ^_~)

Reference Documentation:

1. Liaoche Python Tutorial: Functional programming

Python: Advanced Features of functions

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.