标签:索引 一个 sdi def path 函数 turn 二分 new
递归(难点)
自己调用自己
递归的入口
递归的出口: 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)
标签:索引 一个 sdi def path 函数 turn 二分 new
原文地址:https://www.cnblogs.com/verena/p/9683102.html