From 19bac5748e37e924b44f6bf2fce2bc5b6525324e Mon Sep 17 00:00:00 2001 From: BellCodeEditor <bellcode_dev@bell.ai> Date: Sun, 26 Feb 2023 17:13:04 +0800 Subject: [PATCH] save project --- my_search.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/my_search.py b/my_search.py index 6eaf4dc..0e2beb8 100644 --- a/my_search.py +++ b/my_search.py @@ -1,9 +1,23 @@ import random - alist = [] for i in range(1, 101): alist.append(i) num = random.choice(alist) # 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置 - -def binary_search(alist,num): \ No newline at end of file +def binary_search(alist) +def binary_search(alist,num): + low = 0 + high = len(alist)-1 + while low <= high: + mid = (low + high) // 2 + guess = alist[mid] + if guess == num: + return mid + elif guess < num: + low = mid + 1 + else: + high = mid - 1 + return None +result = binary_search(alist,num) +print("老师给的数是:"num) +print("它在列表里的索引是:"result) -- libgit2 0.25.0