From 6160b4d4e36fc02addbea597ede2cfab0f710a80 Mon Sep 17 00:00:00 2001 From: BellCodeEditor <bellcode_dev@bell.ai> Date: Sat, 1 Jan 2022 11:43:22 +0800 Subject: [PATCH] save project --- my_search.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/my_search.py b/my_search.py index 6eaf4dc..c13b1a5 100644 --- a/my_search.py +++ b/my_search.py @@ -6,4 +6,20 @@ for i in range(1, 101): num = random.choice(alist) # 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置 -def binary_search(alist,num): \ No newline at end of file +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) \ No newline at end of file -- libgit2 0.25.0