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)
添加回答
举报