递归与二分法
递归:在一个函数内再调用这个函数本身
递归的最大深度是997,可以在sys里面修改
def hannuo(n,a,b,c):
if n == 1:
print(a,'-->',c)
else:
hannuo(n-1,a,c,b)#把n-1层放到b
print(a,'-->',c)#把最后一层放到c
hannuo(n-1,b,a,c)#把b上的n-1层放到c
n = int(input('please input one number'))
hannuo(n,'a','b','c')
二分法
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
def two_search(l):
n = len(l)
a = int(input('please input a number'))
left = 0
right = n
while left <= right:
if l[(left+right)//2] < a:
left = (left+right)//2
elif l[(left+right)//2] > a:
right = (left+right)//2
elif l[(left+right)//2] == a:
print('找到了',(left+right)//2+1)
break
two_search(l)
评论已关闭