Python Learning note Five functional programming (i)

Source: Internet
Author: User
Tags abs iterable

Reference Tutorial: Liao Xuefeng official website https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

Function-Type programming

First, higher order function

The so-called high-order function is that a function can take another function as an argument.

The first thing you need to know about Python is that variables can point to functions, as in the following example:

>>> ABS ( -5)5>>> f=abs>>> f<built- in function abs >>>> ABS<built- in function abs>>>> f ( -5)5

You can see that when the variable F points to the function name ABS, F also becomes an absolute name and can be called by F.

The nature of the function name is also a variable, just set the variable directly in Python to point to the function.

>>> abs='ABC' >>> abs'abc'> >> ABS ( -1) Traceback (most recent  ):"<pyshell#7>"  in <module>    abs (-1'str'are   not callable

In the example above, the built-in function name ABS points to a string, then its essence changes, and can no longer invoke its method of calculating the absolute value. (resets only after the next launch of the Python Runtime environment.)

Look at one of the simplest high-order functions (that is, with function names as arguments):

def Funa (a):     return *adef  Funb (a,b,f):    return F (a) +f (b)>>> Funb (3,4, Funa)25

>>> Funb ( -6,-10,abs)
16

(a) Map/reduce

1. Map

The map function accepts two parameters, one is a function and the other is a iterable (an iterative object). Map functions The incoming function sequentially to each element of the sequence and returns the result as a new iterator (iterator).

For example, use Python to implement a function f (x) =x^2, acting on a list.

def FX (N):     return n**2>>> map (fx,[1,2,3,4,5,6,7,8,9])<map object at 0x0000000002da8d30>

Note that the result here is a map object, essentially an iterator (Iterator), from the previous section that the iterator is inert and the result is converted to iterable to output.

>>> list (map (fx,[1,2,3,4,5,6,7,8,9)) [1, 4, 9, +,------ Import  Iterator>>> x=map (fx,[1,2,3,4,5,6,7,8,9])>>> isinstance (x, Iterator) True

Although other methods can also be implemented to generate a result list of the effect, but map as a higher-order function, the process of abstracting the operation rules, in the application can handle more complex functions, such as the following example of a list all the numbers into a string only need a line of code:

>>> list (map (str,[1,2,3,4,5])) ['1'2' ' 3 ' ' 4 ' ' 5 ']

2. Reduce

Reduce also applies a function to a sequence, but the internal process is different from map, reduce is to continue the result of the function and the next element of the sequence to continue to calculate, and this function must accept two parameters, so the effect is:

Reduce (F,[a,b,c,d]) =f (f (f (b) +c) +d)

A simple summation example:

 from Import Reduce def Myadd (A, b    ): return A +b>>> Reduce (myadd,list (range (1,101)))5050

Another example is to turn a number sequence into a number:

def Myadd (A, b    ): return a*10+b>>> reduce (myadd,[1,3,7,9])1379

With map and reduce, you can convert a numeric string to a numeric value:

def Funa (NSTR):     return Int (NSTR)>>> reduce (Myadd,map (Funa,'12345'))12345

Practice:

" " using the map () function, the nonstandard English name entered by the user becomes the first letter capitalized, and the other lowercase canonical names. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']'def  fun1 (stra):      return  stra.capitalize () name_list=['Adam'LISA ' ' BarT ' ]print(list (map (fun1,name_list)))
" "the sum () function provided by Python can accept a list and sum, write a prod () function that accepts a list and uses the reduce () to calculate the product:" "defFun2 (A, b):returnA *bdefprod (lista):returnreduce (Fun2,lista)Print('3 * 5 * 7 * 9 =', prod ([3, 5, 7, 9]))ifProd ([3, 5, 7, 9]) = = 945:    Print('Test Success!')Else:    Print('Test failed!')
 fromFunctoolsImportReduce" "use map and reduce to write a str2float function that converts the string ' 123.456 ' to a floating-point number 123.456" "#idea: First divide the original string into two parts: integers and fractional parts are processed separately#processing conversions for integer parts#1. Convert characters to values firstdefStrtonumbera (char): Mydic={'0'70A'1': 1,'2': 2,'3': 3,'4': 4,'5'75A'5'75A'6': 6,'7': 7,'8': 8,'9': 9}    returnMydic[char]#2. Define the function parameters of the integer section reducedefMyfunca (A, b):returna*10+b#3. Convert an integer string to an integer value by Reduce/mapdefFunca (Strx):returnReduce (myfunca,list (Map (strtonumbera,list (STRX) ))#handle conversion of fractional parts#1, define the function parameters of the small part of reducedefMYFUNCB (A, b):returna/10+b#2. Convert an integer string to an integer value by Reduce/mapdefFUNCB (Strx):#The processing of the fractional part is compared with the whole number, which is the processing in the reduce calculation, which can be reversed first.stry=list (Strx) stry.reverse ()Print(stry) x=Reduce (myfuncb,list (map (strtonumbera,stry)))#It's not the end of the time, it needs to be divided by ten    returnX/10defstr2float (Strx):#Integer PartX=funca (Strx.split ('.') [0])#number of decimal partsY=FUNCB (Strx.split ('.') [1])    returnx+YPrint(Str2float ('123.589'))Print('str2float (\ ' 123.456\ ') =', Str2float ('123.456'))ifABS (Str2float ('123.456')-123.456) < 0.00001:    Print('Test Success!')Else:    Print('Test failed!')

Python Learning note Five functional programming (i)

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.