3 回答
TA貢獻1812條經驗 獲得超5個贊
使用 while 循環,如果找到該數字,則中斷:
while True:
middle_index = (end_index-start_index) / 2
...
elif middle_element == number_to_identify:
print("Number is in the list")
break
順便說一句,我重新拼寫了變量以匹配Python的推薦樣式。
TA貢獻1815條經驗 獲得超6個贊
def identify(num,lst):
start = int((len(lst)/2) - ((len(lst)/2) % 1))
while True:
if num > lst[start]:
start += 1
if num < lst[start]:
start -= 1
if num == lst[start]:
print("Found number at index: {0}".format(start))
return lst[start]
list_of_number=[1,2,3,4,5,6,7]
number_to_identify=6
identify(number_to_identify, list_of_number)
這將為您解決問題。如果列表的長度是偶數,它將從中間右邊的第一個元素開始。
TA貢獻1725條經驗 獲得超8個贊
以下代碼有點笨重。但它會起作用。如果需要進行任何修改,請提出建議,如果我們能使它更容易。
def find_number(list_number,num_to_check):
Start_Index=0
End_Index=len(list_number)-1
new_list=list_number
not_found=False
while len(new_list)>2:
middle_index=(End_Index-Start_Index)/2
middle_Element=new_list[int(middle_index)]
if new_list[0]==num_to_check or new_list[-1]==num_to_check:
print("Number in List")
break
#If number is in Second Half of the list
elif middle_Element<num_to_check:
Start_Index=middle_index
new_list=new_list[int(Start_Index):int(End_Index+1)]
print(new_list)
End_Index=len(new_list)
Start_Index=0
print(End_Index)
not_found=False
#If number is in First Half of the list
elif num_to_check<middle_Element:
End_Index=middle_index
new_list=new_list[int(Start_Index):int(End_Index+1)]
print(new_list)
End_Index=len(new_list)
print(End_Index)
not_found=False
#If Number is match with the middle number
else:
not_found=True
break
if not_found:
print("Number in List")
else:
print("Number not in List")
l1 = [10,22,43,56,65,79,88,92,102]
n1 = 93
find_number(l1,n1)
添加回答
舉報
