Functional programming of Python

Source: Internet
Author: User

First, higher order function

1.map:

Usage: Map (function object, sequence)

Function: Each object in the sequence is scoped to the function's parameters and a new sequence is generated to return

Example: Capitalize the first letter in the list with the remaining letter lowercase in the list

def ordername (name):     Lambda Newname:newname[0].upper () + newname[1:].lower ()    return= ['Adam ' ' LISA ' ' BarT ' ]print map (ordername, LST)

2.reduce:

Usage: Reduce (function object, sequence)

function: Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:

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

Example: A python-provided sum() function can accept a list and sum, write a prod() function that accepts a list and uses the Quadrature reduce() .

def prod (LST):     return reduce (lambda x, y:x*= [1,2,3,4,5,6]print prod (LST)

3.filter

Usage: Filter (function object, sequence)

Function: The filter() incoming function is applied to each element sequentially, and then True(保留) False the element is persisted or discarded based on the return value. Equivalent to a filter.

Example: Using filter () to sieve the prime number of a 1~100

def Mdel (num):     if  num = =1        :return  True    for in range (2, num):         if num% i = = 0            :return     Truereturn  False Print filter (Mdel, Range (1, 101))

# # consider 1 is not a prime and not a composite so should keep 1 # #

4.sorted

Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting, the core of the sort is to compare the size of the 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. It is generally stipulated that for two elements and, if considered, then returned, if considered, then returned, x y x < y -1 x == y 0 If considered x > y , then returned 1 , so that the sorting algorithm does not care about the specific comparison process, Instead, they are sorted directly by comparison results.

You can also use sorted (sequence, custom comparison function) to draw up your own rules for comparison and to get a comparative result.

Example: Comparing a group of names without case (due to direct comparison causes the ASCII code to be judged less than the uppercase value in the lower case)

defmycmp (S1, S2): U1=S1.upper () U2=S2.upper ()ifU1 >U2:return1elifU1 = =U2:return0elifU1 <U2:return-1LST= ['Bob',' About','Zoo',' Credit']PrintSorted (LST, mycmp)

Second, return function

Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters.

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

Calling Lazy_sum does not return the computed value immediately, but instead returns the Sum function object

>>> f = lazy_sum (1, 3, 5, 7, 9)>>> f<function sum at 0x10452f668>

Calling F again will really return the sum value

>>> F ()25

In this example, we define the function in the function lazy_sum sum , and the intrinsic function sum can refer to lazy_sum the parameters and local variables of the external function, and when the lazy_sum function is returned sum , the relevant parameters and variables are stored in the returned function, which is called " The program structure of the closure (Closure) has great power.

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

Third, anonymous function

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

def f (x):     return x * x

The keyword lambda represents an anonymous function, preceded by a colon, that x represents a function parameter.

The anonymous function has a restriction that there can be only one expression, without writing return , and the return value is the result of that expression.

Four, decorative device

Https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 001386819879946007bbf6ad052463ab18034f0254bf355000

Five, partial function

Using partial in Functools to establish a partial function

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

functools.partialis to fix some parameters of a function (that is, to set a default value), to return a new function, and to call the new function is simpler.

Functional programming of Python

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.