我被要求对二进制搜索名称列表进行搜索,如果这些名称以特定字母开头,例如A,那么我将打印该名称。 我可以做更多简单的代码,如如何对以某个字母开头的单词执行二分查找?
for i in list:
if i[0] == "A":
print(i)
完成这个任务,而是要求我使用二进制搜索,我努力理解其背后的过程。我们给出了可以输出给定字符串的位置的基本代码。我的问题是不知道该怎么修改,这样我可以达到理想的结果
name_list = ["Adolphus of Helborne", "Aldric Foxe", "Amanita Maleficant", "Aphra the Vicious", "Arachne the Gruesome", "Astarte Hellebore", "Brutus the Gruesome", "Cain of Avernus"]
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
found = False
while low_b <= up_b and found == False:
midPos = ((low_b + up_b) // 2)
if list[midPos] < item:
low_b = midPos + 1
elif list[midPos] > item:
up_b = midPos - 1
else:
found = True
if found:
print("The name is at positon " + str(midPos))
return midPos
else:
print("The name was not in the list.")
期望的结果
bin_search(name_list,"A")
打印所有的名字开始与HelBorne的A(阿道夫Aldric福克斯....等)
编辑: 我只是做一些猜测和检查,并找到了如何做到这一点。这是解决方案代码
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
true_list = []
count = 100
while low_b <= up_b and count > 0:
midPos = ((low_b + up_b) // 2)
if list[midPos][0] == item:
true_list.append(list[midPos])
list.remove(list[midPos])
count -= 1
elif list[midPos] < item:
low_b = midPos + 1
count -= 1
else:
up_b = midPos - 1
count -= 1
print(true_list)
首先,排序它 - [排序HOW TO(https://docs.python.org/3/howto/sorting.html) – wwii
抱歉,我应该有提到,我给的列表已经排序,所以我们可以跳过那部分,但是是正确的,它需要排序 – oneman
做一个二进制搜索,研究它应该如何工作,研究代码,试图找出如何它可以工作,使用打印语句来帮助*可视化*。 – wwii