基础数据结构复习:
汉诺塔问题
def hannuota(n,a,b,c):
if n > 0:
hannuota(n-1,a,b,c)
print("moving from %s to %s"%(a,b))
hannuota(n-1,c,a,b)
hannuota(3,'A','B','C')
顺序查找(找其索引)
def liner_serach(lst,valu):
for ind,val in enumerate(lst):
if val == valu:
return ind
else:
return None
lst=[1,5,3,8,5,98,31,65,8,1,54,21,]
print(liner_serach(lst,54))
3.二分查找
def binary_search(lst, valu):
left = 0
right = len(lst) - 1
while left <= right: # 定义候选区
mid = (left + right) // 2
if lst[mid] == valu:
return mid
elif lst[mid] > valu:
right = mid - 1
else:
left = mid + 1
else:
return None
lst=[1,5,2,5,32,6,8,5,2,7,84,512,5]
lst.sort()
print(binary_search(lst, 1))