Recursion of Python functions (use recursion to find the sum of 1 to n use recursion to find the nth Fibonacci number to find the sum of numbers in nested lists for quick sorting)

recursive function

Simply put, adjust yourself; the most important thing for recursion is to find the exit (that is, the condition to stop)

cou = 5
def say_love():
    print('我爱你',end=' ')# 把这五个我爱你打在一行
    global cou
    cou = cou-1
    if cou>0:
        say_love()
say_love()# '我爱你 ''我爱你 ''我爱你 ''我爱你 ''我爱你 '

A simple demonstration, but this requires calling a global scalar for judgment, we can also pass parameters directly, and use return to return the function. Please see the following demonstration:

def say_love2(n):
    if n > 0:
        print('我爱你',end=' ')
        return say_love2(n-1)

say_love2(5)# '我爱你 ''我爱你 ''我爱你 ''我爱你 ''我爱你 '

There are other ways of writing, I will not list them one by one.
Let’s do a few simple exercises:

1. Use recursion to find the sum of 1 to n

def mysum(n):
    if n == 1:# 停止条件 当n等于1的时候返回1
        return 1
    return n + mysum(n-1)
    #要是实在还是没理解,可以把这个式子在草稿纸上写出来就很容易看懂了

s = mysum(100)
print(s)# 5050

2. Use recursion to find the nth Fibonacci number

# 斐波那契数列:1,1,2,3,5,8,13,21,34,55....
def feibo(n):
    if n == 1 or n == 2:# 停止条件
    # 后面的数是不是都是由最前面两个数'相加'得来的
    # 这里的相加是指以它两为基数相加得来的
        return 1
    return feibo(n-1)+feibo(n-2)# 第n个数是由前两个数相加得来的

f = feibo(10)
print(f) # 55

3. Find the sum of the numbers in the nested list

You can nest lists, tuples, strings, integers, and floating-point numbers in the list. Here, you need to loop to determine whether it is a number. If it is a list, you need to add it directly. To make a judgment, the nesting is not limited to 2 levels
. The difference between isinstance() and type():
type() does not consider the subclass to be a parent type, regardless of inheritance;
isinstance() considers the subclass to be a parent class Type, consider the inheritance relationship.

lists = [1,2,5,[1,7,3,'a'],(1,2),'abc',3]
def sum_num(n):
    s = 0
    for i in n:
        if isinstance(i,(int,float)):
        # if type(i) == int or type(i) == float:
            s += i
        if isinstance(i,(tuple,list)):
        # if type(i) == tuple or type(i) == list:
            s += sum_num(i)
    return s
print(sum_num(lists))# 25

4. Quick sort

Go to a number in the list, delete it, and traverse the list again. The number larger than the number taken is placed in the right list, and the smaller number is placed in the left list. Finally, the function returns these phases. Plus, you can see the actual operation below, I don't know the possibility, it will harm QAQ

'''
             [4, 2, 6, 7, 5, 1, 3, 8, 9]
             
             [4, 2, 1, 3]          [5]    [6, 7, 8, 9]
             [] [1] [4,2,3]        [5]    [6,7]    [8] [9]
             [] [1] [][2][4,3]     [5]    [6][7][] [8] [9]
             [] [1] [][2][][3][4]  [5]    [6][7][] [8] [9]
'''
def quick_sort(l):
    # 结束条件
    if len(l) <= 1:
        return l
    # 1.取一个元素
    middle = l.pop(len(l)//2)
    # 2.定义2个列表:left,right,分别存放小于middle,和大于middle的元素
    left = []
    right = []
    for n in l:
        if n < middle:
            left.append(n)
        else:
            right.append(n)

    print(left, [middle], right)# 可以用来查看排序的实现
    # 函数递归
    return quick_sort(left) + [middle] + quick_sort(right)
l = [4, 2, 6, 7, 5, 1, 3, 8, 9]
print(quick_sort(l))

Note: try not to use recursion if possible

Recursion is less efficient, and the depth of recursion is limited. If it exceeds this depth, an exception will be thrown.
Here you need to change the depth of recursion, and you need to use the sys module.

import sys
sys.setrecursionlimit(1000000)
Brief summary, do not like, do not spray
Also, if conditions permit, you can like, comment and follow.
QAQ

Guess you like

Origin blog.csdn.net/hmh4640219/article/details/112990437