简体   繁体   English

如何对以某个字母开头的单词进行二进制搜索?

[英]How do I run a binary search for words that start with a certain letter?

I am asked to binary search a list of names and if these names start with a particular letter, for example A, then I am to print that name. 我被要求对名称列表进行二进制搜索,如果这些名称以特定字母开头,例如A,那么我要打印该名称。 I can complete this task by doing much more simple code such as 我可以通过执行更简单的代码来完成此任务,例如

for i in list:
    if i[0] == "A":
        print(i)

but instead I am asked to use a binary search and I'm struggling to understand the process behind it. 但是我被要求使用二进制搜索,而我正努力理解其背后的过程。 We are given base code which can output the position a given string. 我们获得了可以输出给定字符串位置的基本代码。 My problem is not knowing what to edit so that I can achieve the desired outcome 我的问题是不知道要编辑什么以便可以达到期望的结果

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.")

Desired outcome 期望的结果

bin_search(name_list,"A")

Prints all the names starting with A (Adolphus of HelBorne, Aldric Foxe .... etc) 打印所有以A开头的名称(HelBorne的Adolphus,Aldric Foxe ....等)

EDIT: I was just doing some guess and check and found out how to do it. 编辑:我只是在做一些猜测和检查,并找出如何做。 This is the solution code 这是解决方案代码

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)

Not too sure if this is what you want as it seems inefficient... as you mention it seems a lot more intuitive to just iterate over the entire list but using binary search i found here i have: 不太确定这是否是您想要的,因为它似乎效率不高...正如您提到的那样,仅遍历整个列表但使用二进制搜索似乎更直观,我在这里找到

def binary_search(seq, t):
    min = 0
    max = len(seq) - 1
    while True:
        if max < min:
            return -1
        m = (min + max) // 2
        if seq[m][0] < t:
            min = m + 1
        elif seq[m][0] > t:
            max = m - 1
        else:
            return m

index=0
while True:
    index=binary_search(name_list,"A")
    if index!=-1:
        print(name_list[index])
    else:
        break
    del name_list[index]

Output i get: 输出我得到:

Aphra the Vicious
Arachne the Gruesome
Amanita Maleficant
Astarte Hellebore
Aldric Foxe
Adolphus of Helborne

You just need to found one item starting with the letter, then you need to identify the range. 您只需要找到一个以字母开头的项目,然后确定范围即可。 This approach should be fast and memory efficient. 这种方法应该是快速且高效的内存。

def binary_search(list,item):
    low_b = 0
    up_b = len(list) - 1
    found = False
    midPos = ((low_b + up_b) // 2)
    if list[low_b][0]==item:
        midPos=low_b
        found=True
    elif list[up_b][0]==item:
        midPos = up_b
        found=True
    while True:
        if found:
            break;
        if list[low_b][0]>item:
            break
        if list[up_b][0]<item:
            break
        if up_b<low_b:
            break;
        midPos = ((low_b + up_b) // 2)
        if list[midPos][0] < item:
            low_b = midPos + 1
        elif list[midPos] > item:
            up_b = midPos - 1
        else:
            found = True
            break
    if found:
        while True:
            if midPos>0:
                if list[midPos][0]==item:
                    midPos=midPos-1
                    continue
            break;
        while True:
            if midPos<len(list):
                if list[midPos][0]==item:
                    print list[midPos]
                    midPos=midPos+1
                    continue
            break
    else:
        print("The name was not in the list.")

the output is 输出是

>>> binary_search(name_list,"A")
Adolphus of Helborne
Aldric Foxe
Amanita Maleficant
Aphra the Vicious
Arachne the Gruesome
Astarte Hellebore

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历字符串并将以某个字母开头的单词添加到空列表中? - How do I loop over a string and add words that start with a certain letter to an empty list? 查找列表中以某些字母开头的单词 - Find how many words start with certain letter in a list 如何计算二进制搜索树中以&#39;W&#39;开头的单词数 - How to count number of words that start with 'W' in a binary search tree 如何找到以大写字母开头的字符串中的单词? - how can i find the words in a string that start with capital letter? 如何在列表中没有字母&#39;e&#39;的单词上打印? - How do I print the words on a list that do not have the letter 'e'? 如何提取某些单词的第一个字母 - How to extract the first letter of certain words 使用正则表达式匹配不以某个字母开头的单词 - Match words that don't start with a certain letter using regex 如何过滤给定字母中的单词列表? - How do I filter a list of words from a given letter? 二进制搜索“无限”序列。 我从哪里开始? - Binary search over an “infinite” sequence. Where do I start? Python:如何将列表中以某个字母开头的元素复制到新列表中或从列表中删除不以字母开头的元素 - Python: How to copy elements from list that start with a certain letter into new list or remove elements from list that do not start with letter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM