参考链接:
https://www.cnblogs.com/Hades123/p/11019531.html
参考链接:
https://www.cnblogs.com/Hades123/p/11019531.html
递归
什么是函数递归
o函数的递归就是函数的嵌套,之前讲的函数的嵌套是嵌套的别的函数,而递归则是嵌套函数本身
o# 会进入死循环
def f1(): print(‘from f1’) f1() f1()
o以上的函数是一个递归函数,但是这是一个死循环,所以我们需要定一个规则来终止这个函数
def f1(num): if num < 3: f1(num+1) print(num) # 先调用,再进行打印 f1(1)
def f1(num): if num < 3: print(num) # 先打印再进行调用 f1(num+1) f1(1)
直接调用
odef f1(num): if num < 3: print(num) # 先打印再进行调用 f1(num+1) f1(1)
间接调用
o间接调用指的是不在原来的函数体内调用函数本身,而是通过其他方式进行调用
def bar(num):
if num > 0:
o print(num,‘from bar’)
o foo(num)
def foo(num):
print(num,‘from foo’)
bar(num-1)
bar(5)
print(’*’*50)
foo(5)
递归的两个阶段
o递推:一层一层递归调用下去,进入下一层递归的问题规模将会缩小
o回溯:递归必须要m有一个明确的结束条件,在满足该条件时,开始一层一层回溯
o# how many in
line = [1,2,3,4,5,6]
def howmanyin(lst):
if lst[1:]:
o print(lst)
o print(‘me and the guys behind’)
o return 1+ howmanyin(lst[1:])
else:
o print(‘just me’)
o return 1
print(howmanyin(line))
output
[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 behindjust me6
ohttp://www.pythontutor.com/visualize.html#mode=display
用这个链接可视化
二分法
o从一个从小到大排列的数组中,我们需要判断某一个数是否在列表里面
ocode
nums = [1, 3, 7, 11, 22, 34, 55, 78, 111, 115]
for item in nums:
if item == 10:
o print(‘find it’)
o break
else:
print(‘not exists’)
output:
not exists
o对于上面的代码,我们可以通过foe循环进行实现,但如果我们有一个10000个元素的列表,我们需要找到某一个元素,通过for循环无疑需要很久,这时我们就需要换一个更快的方法了,比如二分法
# 随机生成一个长度为1000的列表
from random import randint
lis = [randint(1,1000) for i in range(1000)]
lis.sort()
print(lis)
[1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 5, 6, 8, 8, 9, 9, ……,993, 994, 996, 996, 998]
ocode
code
def search(num,lis):
half = len(lis)//2
if not lis:
o print(‘exsits’)
o return
if num > lis[half]:
o lis = lis[half+1:]
o search(num,lis)
elif num < lis[half]:
o lis = lis[:half]
o search(num,lis)
else:
o print(‘find it’)
search(695,lis)
code
递归的两个阶段
参考链接:
https://www.cnblogs.com/Hades123/p/11019531.html