Python-Functional programming

Source: Internet
Author: User
Tags naming convention

Functional programming is the use of a series of functions to solve the problem, according to general programming thinking, the way we think about the problem is "how to do", and function-based programming thinking is what I want to "do." As for the feature of functional programming is not summarized, we directly take an example to understand what is functional programming.

Lambda expression (anonymous function):

Common functions and anonymous functions are defined in the following way:

# Common Functions def Add (A, b    ): return A + bprint Add (2,3# anonymous function lambda a,b:a +  bPrint Add (2,3)#======== output ===========5

The naming convention for anonymous functions, identified by the LAMDBA keyword, and the left side of the colon (:) indicates that the function receives the parameter (a, b), and the right side of the colon (:) represents the function's return value (A+B).

Because LAMDBA does not need to be named when it is created, it is called an anonymous function ^_^

Map function:

Calculating string Lengths

ABC = ['com','fnng','cnblogs' ] for in range (len (ABC)):    print  len (abc[i]) # ======== output ===========347

Defines an array of ABC strings, calculates the ABC length, and then loops the length of each string in the output array.

Take a look at how the map () function implements this process.

Abc_len = map (len,['hao','fnng','cnblogs ' ])print  abc_len#======== output ===========[3, 4, 7]

Although, the results of the output are the same, but their form is different, the first is a simple numeric value, the map () function output still preserves the format of the array.

Uppercase and lowercase conversions;

Python is provided with, upper () and lower () to convert case.

# Case Conversion ss='Hello world! ' print ss.upper ()  # convert to uppercase print ss.lower ()  # Turn lowercase  #======== output ===========HELLO World!hello world!

Convert by Map () function:

defTo_lower (item):returnitem.lower () name= Map (to_lower,['cOm','fnng','Cnblogs'])Printname#======== Output ===========['com','fnng','Cnblogs']

As we can see in this example, we have written a function toupper, which does not change the value passed in, but simply makes a simple operation of the incoming value and returns it. Then we use it in the map function to clearly describe what we want to do.

Let's see how the normal way is to implement string-case conversions:

ABC = ['cOm','fnng','Cnblogs']lowname= [] forIinchRange (len (ABC)): Lowname.append (Abc[i].lower ())PrintLowname#======== Output ===========['Hao','fnng','Cnblogs']

The map () function plus the lambda expression (anonymous function) allows for more powerful functionality.

# Ask the square # 0*0,1*1,2*2,3*3,.... 8*8squares = map (Lambda x:x*x, Range (9))print  squares#= = = = = = = = = = Output ===========[0, 1, 4, 9, 16, 25, 36, 49, 64]

Reduce function:

def Add (A, b    ): return a+ = reduce (add,[2,3,4])print  add#======== Output ===== ======9

For the reduce function each time it is necessary to process two data, the first selection of 2 and 3, by adding the Add function to get 5, followed by 5 and 4, and then by the Add function processing, and finally get 9.

As we can see in the previous Map function example, the map function only processes one data at a time.

Then we find how simple it is to implement the factorial using the reduce function plus the lambda expression:

# 5 factorial # 5! =1*2*3*4*5print reduce (lambda x,y:x*y, Range (1,6))#======== Output ======= =120

In addition to the map and reduce in Python, there are other functions such as filter, find, all, and any that are auxiliary (other functional languages are also available), which can make your code more concise and easier to read. Let's look at a more complicated example:

#computes the value of an integer in an array Number=[2,-5, 9,-7, 2, 5, 4,-1, 0,-3, 8]count=0sum=0 forIinchRange (len (number)):ifNumber[i]>0:count+ = 1sum+=Number[i]PrintSum,countifCount>0:average= sum/CountPrintAverage#======== Output ===========30 65

If you use functional programming, this example can be written like this:

Number =[2, -5, 9,-7, 2, 5, 4,-1, 0, -3, 8= filter (lambda x:x>= reduce (lambda x, Y:x+y, sum)/len (sum)print  average#======== output ===========5

Finally, we can see that functional programming has the following benefits:

1) The code is much simpler.
2) data sets, operations, and return values are all put together.
3) When you read the code, there is no loop, so you can have fewer temporary variables, and the variables pour out the logic.
4) Your code becomes a description of what you are going to do, not how to do it.

Transferred from: http://www.cnblogs.com/fnng/p/3699893.html

Python functional Programming (RPM)

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.