"Anonymous function and recursion of Python3"

Source: Internet
Author: User
Tags iterable

One, anonymous function and built-in function Supplement 1. Syntax

Python uses the Lambda keyword to create anonymous functions. Anonymity means that a function is no longer defined in a standard form such as a DEF statement.

Grammar:

Lambda [arg1[, arg2, ... ArgN]: expression

Cases:

Common functions

def func (x, y):    return X+yprint (func) print (func)

Output

<function func at 0x102b31f28>3

An equivalent anonymous function

#匿名函数f =lambda x,y:x+yprint (f) Print (f (+))

Output

<function <lambda> at 0x107a55f28>3

2. Use of anonymous functions with built-in functions
    • The use of max,min,zip,sorted
    • Max (Arg1, arg2, *args[, key]) #key =keyfunc
salaries={' E ': +, ' a ': 100000000, ' W ': 10000, ' Y ': 2000}print (max (salaries))  #默认比较key值大小res =zip ( Salaries.values (), Salaries.keys ())  #以values比较print (Max (res))

    • Implement the above functions with anonymous functions
salaries={' E ': +, ' a ': 100000000, ' W ': 10000, ' y ': 2000}def func (k):    return Salaries[k]print (Max (salaries,key= Func)   #传递函数print (max (Salaries,key=lambda k:salaries[k))   #配合匿名函数, compare Valuesprint (min (salaries,key=lambda K:SALARIES[K]))
# print (sorted (Salaries,key=lambda x:salaries[x],reverse=true)) #默认的排序结果是从小到到

Output

Aay

Add:

    • Map (function, iterable, ...)
    • Apply the ' function ' method to each element in the ' iterable ' of the iterated function and return the result as a list.

Cases:

L=[' A ', ' w ', ' Y ']res=map (lambda x:x+ ' _12 ', l) print (res) print (list (res)) nums= (2,4,9,10) Res1=map (lambda x:x**2,nums) Print (list (res1))

Output

<map object at 0x108e0bef0>[' A_12 ', ' W_12 ', ' Y_12 '][4, 16, 81, 100]
    • Reduce (function, sequence[, initial]), value
    • For the item order in sequence, the function must be called with 2 parameters. If there is a 3rd argument, the initial value can continue to be called, returning a value.
L=[1,2,3,4,5]print (Reduce (lambda x,y:x+y,l,10)) #10 +1+2+3+4+5

Output

25

    • Filter (function or None, sequence), list, tuple, or string
    • Execute function (item) on item in sequence and execute the result to True (! =0) item consists of a list/string/tuple (depending on the type of sequence) returned, false exits (0) for filtering.
l=[' A_SB ', ' w_sb ', ' y ', ' Egon ']res=filter (Lambda x:x.endswith (' SB '), L) print (res) print (list (res))

Output

<filter object at 0x10bc43ef0>[' A_SB ', ' W_SB ']

Second, recursive call 1. Define

Recursion is the invocation of itself in a procedure or function, and when using a recursive strategy, there must be a definite recursive end condition called a recursive exit.

Two stages of recursion:

Recursion and backtracking

2. Recursive thinking

Cases:

The factorial function is defined as:
N! = Factorial (N) = 1 * 2 * 3 * ... * n

Then you can look at the factorial function in this way:
Factorial (n) = n!
= N * (N-1)!
= N * (N-1) * (N-2)!
= N * (N-1) * (N-2) * ... * 3 * 2 * 1
= N * Factorial (N-1)

So we have a recursive version of the factorial function:

def factorial (n):    if n = = 0 or N = = 1:return 1    else:return (n * factorial (n-1)) print (factorial (6))

Can be easily obtained, 6! The result is 720.

Each recursive program follows the same basic steps:
1. Initialize the algorithm. A recursive program typically requires a seed value (seed values) to be used at the beginning. To accomplish this task, you can pass arguments to the function, or provide an entry function that is non-recursive, but can set the seed value for recursive calculations.
2. Check that the current value to be processed is already matched to the baseline condition (base case). If it matches, it is processed and returns a value.
3. Redefine the answer with smaller or simpler sub-problems (or multiple sub-problems).
4. Run the algorithm on the sub-problem.
5. Combine the results into an expression of the answer.
6. Return the results.

3. Use

Recursive algorithms are generally used to solve three types of problems:
(1) The definition of the data is defined by recursion. (e.g. Fibonacci function)
(2) The problem solution is implemented by recursive algorithm. Back
(3) The structural form of the data is defined by recursion. (such as the traversal of trees, the search of graphs)

The disadvantage of recursion: recursive algorithm is inefficient in solving problems. In the process of recursive invocation, the system opens up a stack for each layer's return point, local quantity and so on. Too many recursion times can cause stack overflow and so on.

4. Two-point method

L = [1, 2, 10,33,53,71,73,75,77,85,101,201,202,999,11111]def Search (FIND_NUM,SEQ):    If len (seq) = = 0:        print (' Not EXISTS ')        return    mid_index=len (seq)//2    Mid_num=seq[mid_index]    print (seq,mid_num)    if Find_ num > Mid_num:        #in the right        seq=seq[mid_index+1:]        search (find_num,seq)    elif Find_num < mid_ Num:        #in the left        Seq=seq[:mid_index]        search (FIND_NUM,SEQ)    else:        print (' Find it ') search ( 77,l) Search (72,l) search ( -100000,l)

Output

[1, 2, 10, 33, 53, 71, 73, 75, 77, 85, 101, 201, 202, 999, 11111] 75[77, 85, 101, 201, 202, 999, 11111] 201[77, 85, 101] 8 5[77] 77find it[1, 2, 10, 33, 53, 71, 73, 75, 77, 85, 101, 201, 202, 999, 11111] 75[1, 2, 10, 33, 53, 71, 73] 33[53, 71, 7  3] 71[73] 73not exists[1, 2, 10, 33, 53, 71, 73, 75, 77, 85, 101, 201, 202, 999, 11111] 75[1, 2, 10, 33, 53, 71, 73] 33[1, 2] 2[1] 1not exists

"Anonymous function and recursion of Python3"

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.