Commit c08abd8d by BellCodeEditor

save project

parent 60b76b5d
Showing with 0 additions and 50 deletions
from random import randint as rdt, choice as chc
num_list = [22,32,93,233,32,954,992,834,28,110,2,89,77,8,63,3,9954]
guess_num = chc(num_list)
# 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置
def binary_search(alist, num):
'''
Binary search a num.
Alist is want search list,
num is want search number.
'''
low,high = 0,len(alist) - 1
while low <= high:
mid = (low + high)
guess_num = num_list[mid]
if guess_num == num:
return str(mid)
elif guess_num < num:
low = mid + 1
elif guess_num > num:
high = mid - 1
return None
def bubble_sort(alist, reverse = False):
'''
Bubble soft a list.
Alist is want soft list,
reverse is order or reverse order.
'''
for i in range(0, len(alist) - 1):
for j in range(0, len(alist) - 1):
if reverse == False:
if alist[j] < alist[j + 1]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
elif reverse == True:
if alist[j] > alist[j + 1]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
else:
raise TypeError("reverse's type must is bool!")
num_list = bubble_sort(num_list,True)
result = binary_search(num_list,guess_num)
guess_num = str(guess_num)
print("要猜的数字:%s"%(guess_num))
print("它在列表里的索引是:%s"%(result))
print("列表是:%a"%(num_list))
\ No newline at end of file
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