Function programming in python and python function Programming

Source: Internet
Author: User
Tags binary to decimal

Function programming in python and python function Programming

One feature of functional programming is to allow
1. Pass the function itself as a parameter to another function!
2. Return a function!
Python mainly has the following functional programming methods:Concept,FunctionAndSample CodeTo describe.

    • A high-order function as a parameter
      • Map and reduce
      • Filter
    • 2. How to return a function
      • Lambda expression anonymous method
      • Decorator
      • Partial function

I. High-order functions (functions as parameters)

This actually corresponds to the first feature, that is"Pass the function itself as a parameter to another function"Similar to the "function pointer" in C ++, this technology is easy to implement the template technology. The most commonly used is the sort function. See the following code, in python, the sort sequence is small to large by default for the int type. What if we want to customize the sequence? At this time, the "higher-order functions" are powerful.

#!usr/bin/env pythonimport mathL = [0, -1, 8, 20, -99]print sort(L, abs)

As shown above, the abs function is passed as a parameter to sort as a parameter of sort. Why? In fact, the preparation is to take the abs function name as a parameter. in python, a defined parameter is actually a variable stored in the memory, such as the following Interaction:

>>> def fun():...     print 'haha'... >>> fun<function fun at 0x7faf4667f578>>>>

The specific address may be different from what I printed, but it is actually the same as an address, which also verifies the above"Function name is a variable"Statement.

1. map and reduce

These two built-in functions are classic examples of high-order function applications. Let's look at the sample code:

#!usr/bin/env pythondef lala(x, y=2015):    return x % yprint map(lala, range(2000, 2030)

The running result is:[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

#!usr/bin/env pythondef plus(x, y):    return x * yprint reduce(plus, range(1, 5))

The result is:24, That is, 1*2*3*4
In fact, from the above Code and running results, we can guess what the two functions are for. They both accept two parameters. The first one isA function nameAnd the second isA listMap uses each element in the list as a function parameter and returns a list of return values of each function. Note the number of parameters passed in to the function. If multiple parameters are required, the corresponding list must be changed accordingly.
As for reduce, the requirements for the input function are strict, and it must be an even number (excluding the default parameters), because what it does is to execute from the list sequentially, upload the returned value of the last execution to the next element in the list for calculation. The above code is equivalent

A = plus (1, 2) # first take 1st, 2nd elements B = plus (a, 3) # Then return value as the first parameter, take the next element as the second parameter c = plus (B, 4) # Same as print c

What are the functions of these two functions? Only oneGrammer sweet? The answer is no !!! For details, see du Niang.
I think the most meaningful sentence is:"It greatly facilitates programmers to run their programs on distributed systems without distributed parallel programming ".

2. filter

As the name suggests, a filter retains the required data according to the rules you provide. A filter also accepts two parameters. The first one is a function that returns a Boolean value, the second is a list of parameters whose element type is the Boolean function. first look at the sample code:

#!usr/bin/env pythonimport mathdef is_prime(n):    if n <= 1: return False    for i in range(2, (int)(math.sqrt(n)+1)):        if n % i ==0: return False    return Trueprint filter(is_prime, range(1, 101))

The result is:[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
That is, all prime numbers from 1 to 100.

Ii. How to return a function 1. lambda expression (anonymous method)

Python supports Simple lambda expressions, such:

>>> f = lambda x : x * x>>> f<function <lambda> at 0x7faf4667fb18>>>>

That's right. It is used to generate anonymous methods!

"... Lambda expressions and anonymous methods are really just two words for the same thing. the only thing that differs is, "What does the syntax look like" And the lambda expressions are a further evolution of the syntax. but underneath, they do the same thing. they generate methods. you know, they're in-line methods."
-- C # head Architect Anders Hejlsberg

This leads toClosureHow does it return a function? Let's look at the Code:

#!usr/bin/env pythondef f(x):    def fun():        return x * x    return fun>>> f(1).__name__'fun'>>> 

It should be clear here. With the closure, we canUse the parameters of the function to save the current function call scenario !!!As for how to use it, you will be able to understand its advantages, but I still don't know it yet.

2. decorator

The above anonymous method returns "Native function content". What if I want to add the function without changing the source code? Is there a way, the decorator is born... You can see the code for usage:

#! Usr/bin/env pythondef log (func): def haha (* args, ** kw): print 'call % s (): '% func. _ name _ return func (* args, ** kw) return haha @ logdef now (x): print 'Wo cao, % s' % x >>>> now ('12 o'clock ') call now (): wo cao, 12 o'clock >>>

The @ syntax is used to describe the now function using logs. the log function is actually the "closure" mentioned above. here, we simply add a "declaration before calling" to the function. It is similar to adding other methods.
It is worth noting that:
A)"Decorative principles"
@ Log can be seen as the occurrence of such a thing: now = log (now), that is, the original now function is overwritten and becomes a function decorated by the log closure.
B)Function Parameters ???
Here we use the "Universal parameter list": (* args, ** kw), which can be modified regardless of the parameter list of the function to be modified!
For more details, see Liao Da (LDD ).

3. Partial Functions

In fact, this name is from the perspective of Liao Xuefeng's big tutorial. It seems a little too much to be translated, but the partial order in Discrete Mathematics seems to be so literal-literal, so we don't have to worry about naming. what does it do? What kind of function is returned this time?

When the number of parameters of a function is too large and needs to be simplified, you can use functools. partial to create a new function. This new function can fix some parameters of the original function, making it easier to call.
-- From LDD

Take a simple example to understand:

#! Usr/bin/env pythonimport functools # Note: import this module # example code is from LDDint2 = functools. partial (int, base = 2) >>> import functools >>> int2 = functools. partial (int, base = 2) >>> int2 ('000000') 64 >>> int2 ('000000') 85

Convert the binary to decimal, and fix the value of the base parameter. It is also intuitive to refer to the value of "partial" as opposed to "full!

Now, two major aspects of function programming in python have been briefly introduced. Thank you.
Reading ~ Break awareness (⊙ o ⊙ )!

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.