Python day 6 (3) Python functional programming 1, pythonday

Source: Internet
Author: User

Python day 6 (3) Python functional programming 1, pythonday

I. Functional Programming Concepts

A function is an encapsulation supported by Python. By splitting a large code segment into a function and calling a function at a layer, we can break down a complex task into a simple task, this decomposition can be called process-oriented programming. A function is the basic unit of process-oriented programming.

Functional Programming (note that there is an extra "Style")-Functional Programming, although it can also be attributed to process-oriented Programming, its idea is closer to mathematical computing.

Function programming is a programming paradigm with a high degree of abstraction. functions written in Pure Functional programming languages do not have variables. Therefore, any function, as long as the input is definite, the output is definite. This pure function is called with no side effects.

The programming language that allows the use of variables, because the variable state inside the function is not sure, the same input may have different outputs, so this function has side effects.

One feature of functional programming is that you can pass the function itself as a parameter to another function and return a function!

Python provides partial support for functional programming. Because Python allows variables, Python is not a pure functional programming language.

 

Ii. Concepts of Higher-Order Functions

1. variables can point to functions. The built-in function abs is the function itself, and abs (-10) is the function call. F = abs f (-10) and abs (10) have the same meaning.

2. The function name is also a variable.

3. A variable can point to a function. If a function parameter can receive a variable, a function can receive another function as a parameter. Such a function is called a higher-order function.

 

Iii. High-Order Functions

1 filter Function

Andmap()Similarly,filter()It also receives a function and a sequence. Andmap()The difference is that,filter()Apply the input function to each element in sequence, and thenTrueOrFalseDecide whether to retain or discard the element.

def is_odd(n):

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

Delete an empty string from a sequence:
def not_empty(s):    return s and s.strip()list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))


filter()The key to this high-level function is to implement a "filter" function correctly.filter()The function returnsIterator, That is, an inert sequence, so forcefilter()To complete the calculation result, uselist()Function to obtain all results and return list.
 

2 map/reduce Functions

A map()The function receives two parameters, one being a function and the other being an iterable. map sequentially applies the input function to each element of the sequence and returns the result as a new Iterator. Note: Iterator is an inert sequence, which can be returned through list, next, for in.def f(x):

...     return x * x...>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])>>> list(r)
map()The first input parameter isF (function name)That is, the function object itself. As a resultrIsIterator,IteratorIs an inert sequence, therefore, throughlist()The function calculates the entire sequence and returns a list.

 b  reduceApply a function to a sequence[x1, x2, x3, ...], This function must receive two parameters,reduceCalculates the result continuation and the next element of the sequence. The result is:

Reduce (f, [x1, x2, x3, x4]) = f (x1, x2), x3), x4 ). However, you must useFrom functools import reduce import

A function that converts a string to an integer.
From functools import performancedigits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5 ': 5, '6': 6, '7': 7, '8': 8, '9': 9} def char2num (s ): return DIGITS [s] def str2int (s): return reduce (lambda x, y: x * 10 + y, map (char2num, s ))
3 sorted Functions

(1)
Python built-insorted()The function can sort the list:>>> sorted([36, 5, -12, 9, -21]) [-21, -12, 5, 9, 36]

(2) sorted()A function is also a high-level function that can receivekeyFunction to achieve custom sorting, such as sorting by the absolute value:>>> sorted([36, 5, -12, 9, -21], key=abs) [5, 9, -12, -21, 36]
The function specified by the key acts on each element of the list and sorts the result returned by the key function. Thensorted()The function is sorted by keys, and the corresponding elements of the list are returned according to the corresponding relationship.
(3) by default, strings are sorted by comparing the ASCII size.'Z' < 'a', Result, uppercase lettersZLowercase lettersa.

Ignore the case to compare two strings. In fact, convert both strings to uppercase (or both to lowercase) before comparison.

In this waysortedThe key function is passed in to enable case-insensitive sorting:

         >>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)                                ['about', 'bob', 'Credit', 'Zoo']

To perform reverse sorting, you do not need to change the key function. You can input the third parameter.reverse=True:

             >>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)       ['Zoo', 'Credit', 'bob', 'about']









 

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.