Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字符串列表中对字符串进行二进制搜索_Python_Python 3.x_Binary Search - Fatal编程技术网

Python 在字符串列表中对字符串进行二进制搜索

Python 在字符串列表中对字符串进行二进制搜索,python,python-3.x,binary-search,Python,Python 3.x,Binary Search,我有一个字符串排列列表,还有一个词汇表中的单词列表。我想为每个排列找出它是否在单词列表中。我尝试了一个while循环,然后蛮力地强行通过,这给了我一大堆单词列表中的单词。但当我尝试这种二进制搜索时: def binärSökning(word, wordList): first = 0 last = len(wordList) - 1 found = False while first <= last and not found: middl

我有一个字符串排列列表,还有一个词汇表中的单词列表。我想为每个排列找出它是否在单词列表中。我尝试了一个while循环,然后蛮力地强行通过,这给了我一大堆单词列表中的单词。但当我尝试这种二进制搜索时:

def binärSökning(word, wordList):
    first = 0
    last = len(wordList) - 1
    found = False
    while first <= last and not found:
        middle = (first + last)//2
        if wordList[middle] == word:
            found = True
        else:
            if word < wordList[middle]:
                last = middle - 1
            else:
                first = middle + 1
    return found
新单词表是一个更窄的单词表,它可能是,没有什么错,因为它工作时,我尝试暴力


我希望的结果是,当搜索函数返回true时,for循环会将该单词添加到一个集合中,然后在程序完成后呈现给用户。

这对我来说很好。以下是我的代码:

def binrSkning(word, wordList):
    first = 0
    last = len(wordList) - 1
    found = False
    while first <= last and not found:
        middle = (first + last)//2
        if wordList[middle] == word:
            found = True
        else:
            if word < wordList[middle]:
                last = middle - 1
            else:
                first = middle + 1
    return found
以下几点对我来说很好:

>>> NewWordList = ['hello', 'hi', 'how']
>>> listOfWords = ['hi', 'how', 'bye']
>>> foundWords = set()
>>> for word in listOfWords:
        if binrSkning(word, NewWordList):
            foundWords.add(word)

>>> foundWords
set(['how', 'hi'])

如果您有一个单词列表,只需做一个If语句即可,如下所示:

def bomrSkning(word, wordList):
    found = False
    if word in wordList:
        found = True
    return found

你能举个例子说明你所拥有的和你想要得到的吗?例如,一些虚拟数据,以便我们可以复制您的代码。我更新了一些解释。这是我第一次——希望也是最后一次——在函数名中看到日记。我很惊讶它居然能起作用!为了保持良好的顺序,可能会坚持使用非重音字母:)。以后会尽量记住这一点,但这不是本例中的问题。是的,但单词列表大约有20000个单词,所以这不需要花费一些时间来完成吗?您是否以某种方式对单词进行排序,以便更快地找到它们?如果没有,我想不出一个更快的方法单词列表是按字母顺序排列的如果有帮助的话,单词列表的顺序对我来说并不重要,但当我把它插入真实的东西时,它只会告诉我False。我什么也没改,但这不起作用。你能分享一下你插上的东西吗?
>>> NewWordList = ['hello', 'hi', 'how']
>>> listOfWords = ['hi', 'how', 'bye']
>>> foundWords = set()
>>> for word in listOfWords:
        if binrSkning(word, NewWordList):
            foundWords.add(word)

>>> foundWords
set(['how', 'hi'])
def bomrSkning(word, wordList):
    found = False
    if word in wordList:
        found = True
    return found