Commit 7adb57b7 by BellCodeEditor

save project

parent c28e275e
Showing with 25 additions and 5 deletions
import random
alist = []
num_lest = []
for i in range(1, 101):
alist.append(i)
num = random.choice(alist)
num_lest.append(i)
num = random.choice(num_lest)
# 使用二分查找法,找出9和20在列表里面的索引
# 请完善二分查找函数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)
while True:
if not high<low:
mid = (low + high)//2
x = alist[mid]
if x == num:
return str(num) + '在num_list中的索引是'+str(mid)
elif x > num:
high = mid-1
else:
low = mid+1
else:
return str(num) + '不在num_list中'
a = int(input('number'))
print(binary_search(num_lest,a))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment