函数递归
函数递归指的重复‘’直接‘’或‘’间接‘’调用函数本身,这是一种函数嵌套调用的表现形式
python中递归默认深度为998
获取递归深度 :import sys
print(sys.getrecursionlimit())
设置递归深度:sys.setrecursionlimit(2000)
查看当前可承受递归深度
num = 1
def func():
global num
print('from func',num)
num += 1
func()
func()
单纯的递归调用无任何意义
递归
def f1():
print('from f1')
f1()
f1() #进入死循环
——————————————————————————————————————————————————————————————————————————
#我们需要定一个规则来终止这个函数
def f1(num):
if num < 3:
f1(num + 1)
print(num) #先调用再打印
f1(1)
>>>2
1
—————————————————————————————————————————————————————————————————————————
def f1(num):
if num < 3:
print(num)
f1(num + 1) #先打印再调用
f1(1)
>>>1
2
#以上为直接调用,函数本身调用本身
间接调用:
两个函数之间相互调用,间接造成递归
def bar(num):
if num > 0:
print(num,'from bar')
foo(num)
def foo(num):
print(num,'from foo')
bar(num-1)
bar(5)
print('*'*50)
foo(5)
>>>
5 from bar
5 from foo
4 from bar
4 from foo
3 from bar
3 from foo
2 from bar
2 from foo
1 from bar
1 from foo
**************************************************
5 from foo
4 from bar
4 from foo
3 from bar
3 from foo
2 from bar
2 from foo
1 from bar
1 from foo
递归若要有意义,必须遵循两个条件:
1、递推:一层一层递归调用下去,进入下一层递归的问题规模将会缩小,拿到一个更接近结果的结果
2、回溯:递归必须要有一个明确的结束条件,在满足该条件时,开始一层一层回溯
line = [1,2,3,4,5,6]
def howmanyin(lst):
if lst[1:]:
print(lst)
print('me and the guys behind')
return 1+ howmanyin(lst[1:])
else:
print('just me')
return 1
print(howmanyin(line))
>>>
[1, 2, 3, 4, 5, 6]
me and the guys behind
[2, 3, 4, 5, 6]
me and the guys behind
[3, 4, 5, 6]
me and the guys behind
[4, 5, 6]
me and the guys behind
[5, 6]
me and the guys behind
just me
6