Python function programming example

Source: Internet
Author: User

Functional Programming uses a series of functions to solve the problem. According to the general programming thinking, the way we think about the problem is "How to do it ", the way to think about functional programming is what I want to do ". As for the features of functional programming, let's take examples to understand what functional programming is.

Lambda expressions (anonymous functions ):

Definitions of common and anonymous functions:

Copy codeThe Code is as follows:
# Common functions
Def add (a, B ):
Return a + B

Print add (2, 3)


# Anonymous Functions
Add = lambda a, B: a + B
Print add (2, 3)


#========= Output ==================
5

The naming rules of anonymous functions are identified by the lamdba keyword. The left side of the colon (:) indicates the parameters (a, B) received by the function, and the right side of the colon (:) indicates the return value of the function (a + B ).

Because lamdba does not need to be named during creation, it is called the anonymous function pai_^.

Map function:Calculate the string length

Copy codeThe Code is as follows:
Abc = ['com', 'fnng ', 'cnblogs']

For I in range (len (abc )):
Print len (abc [I])

#========= Output ==================
4

Define the abc string array, calculate the abc length, and then cyclically output the length of each string in the array.

Let's see how the map () function implements this process.
Copy codeThe Code is as follows:
Abc_len = map (len, ['hao', 'fnng ', 'cnblogs'])

Print abc_len

#========= Output ==================
[3, 4, 7]

Although the output results are the same, they have different forms. The first is a simple value, and the output of the map () function is still in the array format.

Case-sensitive conversion;

Python provides upper () and lower () to convert the case.
Copy codeThe Code is as follows:
# Case-sensitive Conversion
Ss = 'Hello WORLD! '

Print ss. upper () # convert to uppercase/lowercase
Print ss. lower () # convert to lowercase

#========= Output ==================
Hello world!
Hello world!

Map () function conversion:

Copy codeThe Code is as follows:
Def to_lower (item ):
Return item. lower ()

Name = map (to_lower, ['com', 'fnng ', 'cnblogs'])
Print name

#========= Output ==================
['Com ', 'fnng', 'cnblogs']

In this example, we can see that we have written a function toUpper, which does not change the passed value. It just makes a simple operation on the passed value and returns it. Then, we can use it in the map function to clearly describe what we want.

Let's take a look at how the normal method achieves string case-sensitivity conversion:
Copy codeThe Code is as follows:
Abc = ['com', 'fnng ', 'cnblogs']
Lowname = []

For I in range (len (abc )):
Lowname. append (abc [I]. lower ())

Print lowname

#========= Output ==================
['Hao', 'fnng ', 'cnblogs']

Map () Functions with lambda expressions (anonymous functions) can achieve more powerful functions.

Copy codeThe Code is as follows:
# Square
#0*3,... 8*8
Squares = map (lambda x: x * x, range (9 ))
Print squares

#========= Output ==================
[0, 1, 4, 9, 16, 25, 36, 49, 64]

Reduce function:
Copy codeThe Code is as follows:
Def add (a, B ):
Return a + B

Add = reduce (add, [2, 3, 4])
Print add

#========= Output ==================

The Reduce function needs to process two data items at a time. The Reduce function selects 2 and 3 at the beginning, adds the add function, and obtains 5 and 4, and then processes the data by the add function, finally, get 9.

In the previous map function example, we can see that the map function processes only one data at a time.

 

Then, we found out how simple it is to use the Reduce function and lambda expression to implement factorial:
Copy codeThe Code is as follows:
#5 factorial
#5! = 1*2*3*4*5
Print reduce (lambda x, y: x * y, range (1, 6 ))

#========= Output ==================

In Python, apart from map and reduce, there are also some other functions such as filter, find, all, and any (other functional languages are also available ), it makes your code simpler and easier to read. Let's look at a complicated example:

Copy codeThe Code is as follows:
# Calculate the positive integer value in the array

Number = [2,-5, 9,-7, 2, 5, 4,-1, 0,-3, 8]
Count = 0
Sum = 0

For I in range (len (number )):
If number [I]> 0:
Count + = 1
Sum + = number [I]

Print sum, count

If count> 0:
Average = sum/count

Print average

#========= Output ==================
6

If function programming is used, this example can be written as follows:

Copy codeThe Code is as follows:
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 ==================

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

1) the code is simpler.
2) dataset, operation, and return values are put together.
3) when you read the code, without the loop body, you can drop some temporary variables and reverse the logic of the variables.
4) your code is about describing 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.