Python Advanced (ii)

Source: Internet
Author: User

High-order functions 1. Passing functions as parameters, such functions are called higher-order functions, and functional programming refers to this highly abstract programming paradigm. The map () and reduce () functions are built in 2.Python

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.
Reduce functions a function in a sequence [X1, x2, x3, ...] , the function must receive two parameters, and reduce accumulates the result and the next element of the sequence.

3.filter () function for filtering sequences

Like map (), filter () also receives a function and a sequence. Unlike map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.

The function of filter () is to sift out the eligible elements from a sequence. Because filter () uses lazy calculations, only the filter () results are actually filtered and each time the next filtered element return is returned
def is_palindrome(n):           return n==int(str(n)[::-1])output = filter(is_palindrome, range(1, 1000))print(‘1~1000:‘, list(output))if list(filter(is_palindrome, range(1, 200))) == [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]:    print(‘测试成功!‘)else:    print(‘测试失败!‘)
Note: integers are converted to strings, then the strings are reversed, then integers, and the original numbers are compared. The reason for this to be an integer is because the n you passed in is an integer, and after the flashback is the STR type. Integers and STR cannot be compared. This can also be modified to: Return str (n) = = str (n) [::-1]. The core of 4.sorted sorting is to compare the size of two elements. If it is a number, we can compare it directly, but what if it is a string or two dict? There is no point in directly comparing the size of mathematics, so the process of comparison must be abstracted by functions.

The sorted () function is also a high-order function, and it can also receive a key function to implement a custom sort, such as by absolute size:

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

To reverse order, you do not have to change the key function, you can pass in the third argumentreverse=True:
***

Returns a function closure (comparison of two examples)
def count():    fs = []    for i in range(1, 4):        def f():             return i*i        fs.append(f)    return fsf1, f2, f3 = count()***>>> f1()9>>> f2()9>>> f3()9

The reason is that the returned function refers to the variable I, but it is not executed immediately. When all 3 functions return, they refer to the variable i has become 3, so the final 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.
def count():    def f(j):        def g():            return j*j        return g    fs = []    for i in range(1, 4):        fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()    return fs***>>> f1, f2, f3 = count()>>> f1()1>>> f2()4>>> f3()9
Example: Use a closure to return a counter function that returns an incremented integer each time it is called
def createCounter():    i = 0    def counter():        print(i)        i += 1        return i    return counter

def createCounter():    i = [0]    def counter():        i[0] += 1        return i    return counter

You can also use the generator

def createCounter():    def num():        n = 1        while 1:            yield n            n = n + 1    n = num()    def counter():        return next(n)    return counter

Python Advanced (ii)

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.