递归
def func3(x):
if x>0:
print(x)
func3(x-1)
def func4(x):
if x > 0:
func4(x - 1)
print(x)
#输出结果:
4
3
2
1
=====================
1
2
3
4
汉诺塔问题
max=0
def hanoi(n,a,b,c):
#统计移动的次数
global max
if n>0:
max = max + 1
hanoi(n-1,a,c,b)
print("moving from %s to %s"%(a,c))
hanoi(n-1,b,a,c)
hanoi(4,'A','B','C')
print("一共移动了%s次"%max)
顺序查找
'''
时间复杂度是O(n)
'''
def liner_search(li,val):
#enumerate()用于可迭代\可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标.
for ind,v in enumerate(li):
if v==val:
return ind
else:
return None
顺序查找
其中列表li必须为有序
'''
时间复杂度为O(logn)
'''
def binary_search(li,val):
left=0
right=len(li)-1
while left<=right: #候选区有值
mid=(left+right)//2
if li[mid]==val:
return mid+1
elif li[mid]>val:
right=mid-1
else:
left=mid+1
else:
return None
li=[1,2,3,4,5,6,7,8,9]
print(binary_search(li,1))