Python Learning Functional programming.py

Source: Internet
Author: User
Tags closure uppercase letter wrapper

Print (ABS (-10)) # function can be variable f = ABSF ( -10) def add (x,y,f): Return f (x) + f (y) x = -5y = 6f = abs# Simple Functional Programming print (Add (x,y,f)) # High The Order function # map/reduce# map () function receives two parameters, one is a function, and the other is ITERABLE,MAP functions the incoming function to each element of the sequence sequentially and returns the result as a new iterator. def f (x): return x * XR = map (f, List (range (1,10))) Print (list (r)) # Reduce#reduce a function in a sequence [X1, x2, x3, ...] , #这个函数必须接收两个参数, reduce results in a cumulative calculation of the next element of the sequence, with the effect of: #reduce (f, [X1, x2, X3, x4]) = f (f (x1, x2), x3), x4) from Functools Impo RT reducedef Add (x, y): return x + yr = reduce (add, [1,3,5,7,9]) print (R) def fn (x, y): return x * + yr = reduce (FN, [1,3,5,7,9])  Print (r) # with map write a function to convert str to int def char2num (s): digits = {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ' 7, ' 8 ': 8, ' 9 ': 9} return digits[s]r = Reduce (Fn,map (char2num, ' 13579 ')) print (r) digits = {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8, ' 9 ': 9}def char2num (s): Return digits[s]def Str2Int (s): Return reduce (Lam BDA x, y:x * + y, map (Char2num, s)) R = Char2num (' 5 ') Print (r) r = Str2Int (' 13579 ') print (R) # exercise # using the map () function, the user enters an irregular English name into an uppercase letter, and other lowercase canonical names. # input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']:def Normalize (name): Return name.capitalize () # test: L1 = [' Adam ', ' LISA ', ' barT ']L2 = List (map (normalize, L1)) print (L2) # Python provides the sum () function to accept a list and sum, # Write a prod () function, can accept a list and use the reduce () Quadrature: def func (x, y): return x * ydef prod (l): return reduce (func, L) print (' 3 * 5 * 7 * 9 = ', prod ([3, 5, 7, 9])) If prod ([3, 5, 7, 9]) = = 945:print (' Test succeeded! ') Else:print (' Test failed! ') # Use map and reduce to write a str2float function # Convert the string ' 123.456789 ' to a floating-point number 123.456789:def str2float (s): # idea: Map will change 123.456789 to 12345679    8, that is, use the slice of the string to skip the decimal point def char2num (s): return digits[s] # n = S.index ('. ') gets the subscript of the decimal point n = 3 N = S.index ('. ') # The Reduce function turns [123456789] into an integer, divided by ten ^ n1, N1 = Len (s)-n-1 = 10-3-1 = 6 N1 = Len (s)-n-1 return reduce (Lam BDA X,y:x*10+y,map (char2num,s[:n]+s[n+1:])/(10**N1) print (' Str2float (\ ' 123.456789\ ') = ', Str2float (' 123.456789 ')) IfABS (Str2float (' 123.456789 ')-123.456789) < 0.00001:print (' Test succeeded! ') Else:print (' Test failed! ') # filter # Python The built-in filter () function is used to filter the sequence. # accepts a function and a sequence in which the function sequentially acts on each element in the sequence, depending on whether the return value is True or False to determine whether to retain or discard the element def is_odd (n): return n%2 = = 1L = List (filter (is_odd, [1 , 2,3,4,5,6,7,8,9,10])) the print (L) # filter () function returns a iterator# need to get all the results with the list () function and return to the list. # delete null characters in a sequence # the Python strip () method is used to remove the character specified by the string Kinsoku (the default is a space). Returns a new string that is generated by removing the string from the Kinsoku specified character. # empty string ("") is false, all other strings are true def not_empty (s): return S and S.strip () L = List (filter (Not_empty, [' A ', ' ', ' B ', None, ' C ', '  ']) print (L) # Filter for prime number of sieve "" First, list all natural numbers starting from 2, construct a sequence: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... Take the first number of the sequence 2, it must be prime, and then sift away with 2 multiples of 2 of the sequence: 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... Take the first number of the new sequence 3, it must be a prime, and then sift away with a multiple of 3 of the 3 sequence: 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... Take the first number of the new sequence 5, and then sift out the multiples of 5 in 5 Series: 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... Keep sifting down and you can get all the primes. ' # _odd_iter: Odd sequence Generator starting from 3 Iteratordef _odd_iter (): n = 1 while true:n = n + 2 yield n# filter function def _not_divisiable (n): return lambda x:x% n & Gt         0# generator constantly returns the next prime number Def primes (): yield 2 it = _odd_iter () # Iterator while true:n = Next (IT) # Iterator First        Yield N it = filter (_not_divisiable (n), it) # to filter out the number that is divisible by the first item # prints the prime number within 20 for n in primes (): If n < 20: Print (n) else:break# Exercise: # The number of digits is read from left to right and read from right to left, for example, 12321,909.    Please filter the number of returns using filter (): Def _iter_ (): n = 0 while True:yield n n = n + 1def palindrome (n): s = str (n) i = 0 J = Len (s)-1 while i<j:if s[i]! = S[j]: return False else:i = i + 1 j = j-1 return trueoutput = Filter (palindrome, range (1,200)) L = list (output) print (l) # sorted sort Algorithm # if it's a number , we can compare directly, but what if it's a string or two dict? There is no point in directly comparing the size of mathematics, so the process of comparison must be abstracted by functions. # Python's built-in sorted () function lets you sort the list: print (sorted ([36, 5, 12, 9, 21])) # In addition, the sorted () function is also a high-order function, and it can also receive a key function to implement a custom sort, For example, by absolute sizeSort # Key The function specified will be applied to each element of the list and sorted according to the result returned by the key function. Print (sorted ([5, -12, 9, -21], Key=abs)) # string Sort L = sorted ([' Bob ', ' about ', ' Zoo ', ' credits ']) print (L) # Ignore case sort: # that requires key This function is applied to all elements, all of which are lowercase and then compared, so that is: L = sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], Key=str.lower) print (l) # reverse order L = sorted ([' Bob ', ' About ', ' Zoo ', ' credits '], Key=str.lower, reverse=true) # print (L) # from the above example, it can be seen that the abstraction of higher-order functions is very powerful, and that the core code can be kept very concise. # Exercise: # Use a group of tuples to represent student names and grades: # Please use sorted () to sort the above list by first name, by grade L = [(' Bob ', * *), (' Adam ', * * *), (' Bart ', $), (' Lisa ', "]#") Tips Selector The element method in the group is the same as the array. def by_name (t): return t[0]def By_grade (t): return T[1]L2 = sorted (l,key=by_name) print (L2) L2 = sorted (l,key=by_grade ) print (L2) # function as return value # The higher order function can accept the function as a parameter, or the function can be returned as a result # variable parameter summation def calc_sum (*args): Ax = 0 for n in args:ax = ax + n Return ax# If you do not need to sum immediately, but in the following code, as necessary to calculate what to do?        Instead of returning the result of a summation, you can return a function that sums it: Def lazy_sum (*args): def sum (): Ax = 0 for n in args:ax = ax + N Return AX return sum# when we call Lazy_sum (), the return is not a summation, but a summation function: F = lazy_sum (1,3,5,7,9) print (f) # <function Lazy_sum.<locals>.sum at 0x0227e8e8># re-call F is the real calculation result print (f ()) # 25# In this example, we define the function sum in the function lazy_sum, and the inner function sum can refer to the parameters and local variables of the external function lazy_sum, and when Lazy_sum returns the function sum, the relevant parameters and variables are stored in the returned function, which is called The program structure of the "Closure (Closure)" has great power. # when returning a function, keep in mind that the function is not executed, and do not refer to any variables that may change in the return function. # Anonymous functions & lambda calculus # When you pass in a function, there are times when you don't need to explicitly define a function, and it's easier to pass in an anonymous function directly. # Python provides limited support for anonymous functions.  L = List (map (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) print (l) # anonymous function Lambda x:x * x is actually: def f (x): return x * XL = List (map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print (L) # The anonymous function has a restriction that there can be only one expression, without writing return, the return value is the result of the expression. # There is a benefit to using anonymous functions because the function has no name and does not have to worry about the function name conflict. In addition, the anonymous function is also a function object, you can also assign the anonymous function to a variable, and then use the variable to invoke the function: F1 = lambda x:x * XL = List (map (F1, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print (L) # with The anonymous function can also be returned as a return value, for example: Def build (x, y): Return lambda:x * x + y * y# exercise: Please use the anonymous function to transform the following code: Def is_odd (n): return n% 2 = = 1L = List (filter (is_odd, range (1))) print (l) L = List (filter (lambda x:x% 2 = = 1, range (1,20))) print (l) # Python's support for anonymous functions Holding Limited,Anonymous functions can be used only in some simple cases. # adorner # function is also an object # function has a __name__ property can get the function name def now (): Print ("2018-05-02") print (now.__name__) f = nowprint (f.__name__) " Now, let's say we're going to enhance the function of the present () function, for example, to automatically print the log before and after a function call, but you don't want to modify the definition of the now () function, which is called an "adorner" (Decorator) in a way that dynamically adds functionality during code execution. "# In essence, decorator is a higher-order function that returns a function. # *args: Variable parameter # **kw: keyword parameter def log (func): Def wrapper (*args, **kw): Print (' Call%s (): '% func.__name__) re Turn func (*args, **kw) returns wrapper# log because it is a decorator, so takes a function as an argument and return a function. # with Python's @ syntax, place decorator at the definition of the function: @logdef now1 (): Print (' 2018-05-02 ') # calls the Now1 () function, not only runs the Now1 () function itself, but also runs Now1 () A line of logs is printed before the function: # put the @log at the definition of the Now1 () function, equivalent to executing the statement: Now1 = log (Now1) now () Now1 () "Because log () is a decorator, the accepted parameter is the original" Now, so, The original Now1 () function still exists, but the NOW1 variable with the same name now points to the new function, so calling Now1 () will execute the new function, the wrapper () function returned in the log () function. Within the wrapper () function, the log is printed first, followed by the original Now1 function. Log () returns a function, which is wrapper. The parameter definition of the wrapper () function is (*args, **kw), so the wrapper () function can accept calls of arbitrary arguments. If the decorator itself needs to pass in parameters, it is necessary to write a higher-order function that returns decorator, which is more complex to write.      For example, the text of the custom log "def log (text): Def decorator (func):  def wrapper (*args, **kw): Print ('%s%s (): '% (text, func.__name__)) return func (*args, **kw) Return wrapper return decorator# this 3-layer nested decorator usage is as follows: @log (' Execute ') def now2 (): Print (' 2018-05-02 ') Now2 () # to IS completed# partial function # Python's Functools module provides a number of useful features, one of which is the partial function # by setting the default value of the parameter, you can reduce the difficulty of the function call. The partial function can do this, too. the # int () function converts a string to an integer, and when only the string is passed in, the Int () function defaults to decimal conversion: print (int (' 12345 ')) # but the Int () function also provides an additional base parameter with a default value of 10. If you pass in the base parameter, you can do an n-ary conversion: print (int (' 12345 ', base = 8)) print (int (' 12345 ', 16)) # Assuming that you want to convert a large number of binary strings, it's very troublesome to pass in int (x, base=2) every time, # So, we thought, can define a function of Int2 (), by default base=2 into: Def int2 (x, base = 2): return int (x, base) print (Int2 (' 10000000 ')) print (Int2 (' 10101010 ') # functools.partial is to help us create a partial function, # We don't need to define INT2 (), we can create a new function directly using the following code int2:import FUNCTOOLSINT2 = functools.partial (int, base = 2) print (Int2 (' 10000000 ')) print (Int2 (' 10101010 ')) print (Int2 (' 10000000 ', base=10)) When print (Int2 (' 10101010 ', base=10)) ' Creates a partial function, it can actually receive the 3 parameters of the function object, *args, and **kw, passing in: Int2 = functools.partial (iNT, base=2) actually fixed the keyword parameter base of the int () function, i.e.: Int2 (' 10010 ') equals: kw = {' base ': 2}int (' 10010 ', **kw) when incoming: Max2 = Functools.partial (max, 10) will actually automatically add 10 as part of the *args to the left, namely: Max2 (5, 6, 7) equals: args = (ten, 5, 6, 7) max (*args) results are 10. ' # When a function has too many arguments and needs to be simplified, use functools.partial to create a new function that can fix some of the parameters of the original function, making it easier to invoke.

Python Learning functional programming.py

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.