[python] recursive function

recursive definition

Recursive function: This function calls itself internally. The function calls itself, implementing recursion.

Recursive features:
1. Remember that all recursive functions have an exit condition
2. There is a close connection between two adjacent repetitions, the former prepares for the latter (usually the output of the former is used as the input of the latter ).
3. The recursion efficiency is not high, and too many recursive levels will lead to stack overflow (in computers, function calls are implemented through the data structure of the stack, and whenever a function call is entered, a stack frame will be added to the stack. , every time the function returns, the stack will decrease by one stack frame. Since the size of the stack is not infinite, too many recursive calls will lead to stack overflow)

Ordinary algorithm to achieve Gaussian summation:

def sum(munber):
    total=0
    for i in range(1,munber+1):
        total+=i
    return total
print sum(100)

operation result:

5050

If using recursive method:

def sum_number(number):
    if number==0:
        return False
    return sum_number(number-1)+number
    # 第一次是sum_number(99)+100的值
    # 第二次是sum_number(98)+99的值
    # 最后一个是sum_number(0)
print sum_number(100)

operation result:

5050

Referring to the next interview question:

res = [lambda x:x+i for i in range(10)]
print res[0](10)

operation result:

 19

explain:

res其实就是[lambda x:x+i,lambda x:x+i,lambda x:x+i,lambda x:x+i,lambda x:x+i,lambda x:x+i,lambda x:x+i,lambda x:x+i,lambda x:x+i,lambda x:x+i]的列表。

res[0] is to take the first element of the list, which is –>lambda x:x+i(10). The anonymous function passes the parameter 10 to the parameter x, and the value of i is the for i in range(10) defined above.
The function looks for the variable when it is called, res[0] is equivalent to lambda x:x+i, and the 10 of res[0](10) in the requirement is the value of the incoming x. The value of i at the end of the traversal is 9, so the value of the reference i is 9.

Python Interview Questions

Personal blog: www.langzi.fun
welcome to exchange Python development, security testing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324855359&siteId=291194637