python-Functional Programming Example Tutorial

Source: Internet
Author: User
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:


#普通函数def Add (A, B):

   Return a + bprint Add (2,3) #匿名函数add = lambda a,b:a + bprint Add (2,3) #======== output ===========55


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 I 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.


#大小写转换ss = ' Hello world! '
Print Ss.upper () #转换成大写print ss.lower () #转换成小写 #======== output ===========hello World!hello world!


Convert by Map () function:


def to_lower (item):    return item.lower () name = Map (to_lower,[' cOm ', ' fnng ', ' cnblogs ')) Print name#======== 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 = []for i in Range (LEN (ABC)):    lowname.append (Abc[i].lower ()) Print lowname#== ====== output ===========[' hao ', ' fnng ', ' cnblogs ']

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

#求平方 #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+badd = reduce (add,[2,3,4]) print add#======== output ===========9 for the reduce function each time you need to process two data, first select 2 and 3, by adding the Add function to get 5, followed by 5 and 4, and then processed by the Add function, 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阶乘 #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:

#计算数组中正整数的值number =[2, -5, 9,-7, 2, 5, 4,-1, 0, -3, 8]count = 0sum = 0for i in range (len (number)):

If number[i]>0:        count + = 1        sum + = Number[i]print sum,countif count>0:    average = sum/countprint average

#======== 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]sum = filter (lambda x:x>0, number) average = 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.

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.