1. 程式人生 > >遞歸和二分法

遞歸和二分法

條件 return lse else 二分 關鍵字參數 print 思想 int

遞歸(難點)
自己調用自己
遞歸的入口
遞歸的出口: return
遞歸的循環條件:動
循環樹形結構

# import os
# def func(file_path,ceng):
# lst = os.listdir(file_path)
# for file in lst:
# full_path = os.path.join(file_path, file)
# if os.path.isdir(full_path):
# print("\t"*ceng, file)
# func(full_path, ceng+1)
# else:
# print("\t"*ceng, file)
# else:
# return
# func("F:\python視頻",0)


二分法查找
核心思想: 掐頭結尾取中間.
前提條件: 有序.

lst = [1, 8, 16, 32, 55, 78, 89, 1, 5, 4, 1, 3, 4, 8, 9, 5]
# #二分法查找數字首先要排序
lst = sorted(lst)
# print(lst)
#[1, 1, 1, 3, 4, 4, 5, 5, 8, 8, 9, 16, 32, 55, 78, 89]
n = int(input("請輸入一個數字: "))
left = 0
right = len(lst)-1
while left <= right:
mid = (left + right) // 2 #索引只能是整數
if n > lst[mid]:
left = mid+1
elif n < lst[mid]:
right = mid - 1
else:
print("剛剛好,所在位置%s" % mid)
break
else:
print("查找的數不存在")
#函數第一套方案
def func(n,lst):
left = 0
right = len(lst)-1
if left <= right:
mid = (left+right)//2
if n > lst[mid]:
new_list = lst[mid+1:]
return func(n, new_list)#####################
elif n < lst[mid]:
new_list =lst[: mid]
return func(n, new_list)#####################
else:
print("剛剛好,所在位置%s"% mid)
return True
else:
return False
print(func(3, lst))
#函數第二套方案
def func(n, lst, left, right):
if left <= right:
mid = (left+right)//2
if n > lst[mid]:
left = mid + 1
elif n < lst[mid]:
right = mid - 1
else:
return True
return func(n, lst, left, right)
else:
return False
ret = func(89,lst,0,len(lst)-1)
print(ret)
#關鍵字參數
def func(n, lst, left=0, right=None):
if right == None:
right = len(lst)-1
if left <= right:
mid = (left+right)//2
if n > lst[mid]:
left = mid + 1
elif n < lst[mid]:
right = mid - 1
else:
return True
return func(n, lst, left, right)
else:
return False
ret = func(90,lst)
print(ret)

遞歸和二分法