Python Notes 3#python Functional programming

Source: Internet
Author: User

▲ Functional Programming Function programming

function when Python built-in support for a package. We can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, and this decomposition can be called process-oriented programming. function is the basic unit of process-oriented program design.

Functional programming can also be attributed to the process-oriented programming, but its ideas are closer to mathematical calculations.

Functional programming is a highly abstract programming paradigm, and functions written in purely functional programming languages have no variables.

One feature of functional programming is that it allows you to pass the function itself as a parameter to another function, and also allows you to return another function.

Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

▲ Higher order functions Higher-order function

A variable can point to a function. The function name is also a variable, which is actually a variable pointing to the function.

A variable can point to a function, and the argument of a function can accept a variable. Then a function can receive another function as a parameter, which is called the higher order function.

If you point a python built-in function name to another object, you cannot call the function through the variable name and error. The sample code is as follows:

>>> ABS ( -10)10>>> abs<built- in function abs>>>> f =  ABS>>> F ( -12)12>>> f<built-indef  Add (x, Y, f): ...      return f (x) + f (y) ... >>> Add ( -10, 22, ABS)

▲map/reduce

The map () function receives two parameters, a function, and a list. Map functions The incoming function to each element of the list in turn and returns the result as a new list. The sample code is as follows:

>>>deff (x): ...returnX *x ...>>> map (F, List (range 1,11)))<map Object at 0x017c0ed0>>>> list (map (f, List (range 1, 11))))[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]>>> list (map (str, list (1, 11))))['1','2','3','4','5','6','7','8','9','Ten']

Reduce takes a function on a list, and the function must receive two parameters. Reduce keeps the result and the next element of the sequence in a cumulative calculation. The sample code is as follows:

>>>deff (x, y): ...returnX * 10 +y ...>>>ImportFunctools>>> Functools.reduce (f, [1, 3, 5, 7, 9])13579#convert char to int type>>>defChartoint (s): ...return{'0'70A'1': 1,'2': 2,'3': 3,'4': 4,'5'75A'6': 6,'7': 7,'8': 8,'9': 9}[s] ...>>> functools.reduce (F, Map (Chartoint,'13579'))13579

▲filter

Python's built-in filter () function is used for filtering sequences. Filter also receives a function and a sequence. Unlike map (), filter () determines whether the element is persisted or discarded depending on whether the function is true or FALSE for each element's return value. The sample code is as follows:

def is_odd (n): ...      return n% 2 = = 1... >>> Filter (is_odd, list (range)) <filter object at 0x017c0f70>>>> list ( Is_odd, List (range))[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

▲sorted

For numbers, we can compare sizes directly. But for a string or dict, the direct comparison of mathematical size is meaningless. Therefore, the process of comparison must be abstracted through functions. Normally, X<y returns -1,x=y return 0,x>y returns 1.

Sorts the strings by default by the size of ASCII.

The sample code is as follows:

>>> Sorted ([12, 23, 4, 34, 6])[4, 6, 12, 23, 34]>>> Sorted (['Wddoer','IBM','Apple','MIUI'])['IBM','MIUI','Apple','Wddoer']#Case-insensitive sorting>>> Sorted (['Wddoer','IBM','Apple','MIUI'], key =str.lower) ['Apple','IBM','MIUI','Wddoer']

▲ return function

In addition to the ability to accept functions as parameters, the higher-order functions can also return functions as result values. The sample code is as follows:

def lazy_sum (*args): ...      def sum (): ...          = 0          ...  for inch args:              ... = i + n ...          return I      ... return sum ... >>> f = lazy_sum (1, 2, 3, 4, 5)>>> F<function lazy_sum.<locals>.sum at 0 X017c43d8>>>> F ()15

▲ Anonymous function lambda

There is a limit to the anonymous function, that is, there can be only one expression, no thanks to return, the return value is the result of the expression. An anonymous function is also a function object. The sample code is as follows:

>>> map (lambda x:x * x, List (range (1, one)))<map object at 0x017ca090>>>> list (  Map (Lambda x:x * x, List (range (1, one)))) [1, 4, 9, +, +,, +, +, Bayi, +]Lambda X:X * x>>> F<function <lambda> at 0x01808b28>

▲ Decorator of decorative device

The way to dynamically add functionality during code runs is decorator. In addition to supporting object-oriented (OOP) decorator, Python supports decorator directly from the syntax hierarchy. Python's Decorator

can be implemented using functions or classes.

The function object has a __name__ property that can be used to get the name of the letter

With Python's @ syntax, we can put decorator as a function definition

The sample code is as follows:

>>>defNow (): ...Print('2015-1-28')...>>>Now ()2015-1-28>>> f = Now>>>f ()2015-1-28>>> F.__name__' Now'#define a decorator that can print logs>>>deflog (func): ...defWrapper (*args, * *kw): ..Print('Call %s ():'% func.__name__)...         returnFunc (*args, * *kw) ...returnwrapper ...#use the @ syntax to decorator the definition of a function>>>@log ...defNow (): ...Print('2015-01-28')...>>>Now () Call Now ():2015-01-28>>>log (now)<function Log.<locals>.wrapper at 0x01808a50>>>> now.__name__'wrapper'

▲ Partial function

Python's Functools module provides a number of useful functions, one of which is the partial function.

The function of a partial function is to fix some parameters of a function (set default values) and return a new function. It is easier to call this new function.

When you create a partial function, you can actually accept the three parameters of the function object, *args,**kw (keywords).

The sample code is as follows:

#converting a string into binary>>> Int ('1111', base=2)15>>> Int ('1111', base=8)585>>> Int ('1111', base=10)1111>>> Int ('1111', base=16)4369#Import Functools Module>>>ImportFunctools#defines a partial function int2, which converts the passed-in string arguments into binary>>> Int2 = functools.partial (int, base = 2)>>> Int2 ('1111')15

Python Notes 3#python Functional programming

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.