recursive use python

First, what is a recursive function?

Nested call function is: function nested functions. Recursive function calls: it is a special kind of nested call, but it calls a function of the process, and directly or indirectly calls itself.

1.1 Direct call

Direct call means: direct call function within the function itself.

import sys
print(sys.getrecursionlimit()) #打印最大递归层数:3000
import sys
sys.setrecursionlimit(10000)
def f(n):
    print('from f',n)
f(0)
1.2 indirect call

Indirect call means: do not call the original function in vivo function itself, but to call the function itself through other indirect methods.

def func1():
    print('func1')
    func2()
def func2():
    print('func2')
func1()
Recursive must have two distinct phases:
1.递归:一层一层递归调用下去,进入下一层递归的问题规模都将会减小

2. retrospective: there must be a clear recursive end condition, beginning in the back layer by layer satisfy this condition.

The essence is that by repeating recursive approach a final result constantly.

Second, why use recursion

Recursive nature is doing repeat jobs, but just plain repetition, we use a while loop it.

For example: 1 + ... + 5 is calculated, and

def sum1(i):
    if i == 5:
        return i
    res = sum1(i+1)+i
    print(res)
    return res
print(sum1(1))

Third, how to use recursion?

There is a list of numbers from small to large array of integers, we judge a certain figure is not in the list inside.

Action figure binary searching for the number 7:

lt = [11,33,55,44,77,1,2,86,100]
#      0  1  2  3  4 5 6  7   8
def findnum(f_num,nums):
    if not nums:
        print('没找到')
        return
    lens = len(nums)//2
    if f_num > nums[lens]:
        nums = nums[lens+1:]
        findnum(f_num,nums)
    elif f_num < nums[lens]:
        nums = nums[:lens]
        findnum(f_num, nums)
    else:
        print(f'找到了')
lt.sort()
findnum(7,lt)

Guess you like

Origin www.cnblogs.com/cheng825/p/11352402.html
Recommended