【发布时间】:2016-10-24 08:33:03
【问题描述】:
我正在做一个 Python 练习,从给定的排序 wordlist 中搜索一个 word,包含超过 100,000 个单词。
使用Python bisect module中的bisect_left时效率很高,但使用自己创建的二进制方法效率很低。谁能解释一下为什么?
这是使用 Python bisect 模块的搜索方法:
def in_bisect(word_list, word):
"""Checks whether a word is in a list using bisection search.
Precondition: the words in the list are sorted
word_list: list of strings
word: string
"""
i = bisect_left(word_list, word)
if i != len(word_list) and word_list[i] == word:
return True
else:
return False
我的实现真的非常低效(不知道为什么):
def my_bisect(wordlist,word):
"""search the given word in a wordlist using
bisection search, also known as binary search
"""
if len(wordlist) == 0:
return False
if len(wordlist) == 1:
if wordlist[0] == word:
return True
else:
return False
if word in wordlist[len(wordlist)/2:]:
return True
return my_bisect(wordlist[len(wordlist)/2:],word)
【问题讨论】:
-
因为您实际上并没有使用二分搜索?
-
@jonrsharpe,我尝试实现二分查找,我搜索开始的一半,如果不是开始的一半,我搜索另一半
-
这里的问题是您在每个级别上都制作了列表的副本,这将使您从执行二分搜索中获得的任何好处都相形见绌。尝试仅使用索引来区分要搜索的部分。
-
此外,您正在执行“if word in xxx”,它将进行循环和比较。这根本不是二分搜索。
-
if word in wordlist[len(wordlist)/2:]将使 Python 搜索您的wordlist的一半,这完全违背了编写二进制搜索的目的。请注意,二进制搜索仅适用于排序列表。
标签: python recursion binary-search