gpt4 book ai didi

python - 查找列表中元素的索引。二分查找还是使用索引函数?

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:18 28 4
gpt4 key购买 nike

我是 python 的新手,一直在编写一个练习程序来根据 400 万个单词的列表检查密码。我原来的解决方案是这样的(如果密码包含在列表中,将打印 true):

import sys
from bisect import bisect_left

script, password, pwlist = sys.argv
password = password+"\r\n"

l=[line for line in open(pwlist)]
l.sort() #Must be sorted for bisect_left to work

print (password <= l[-1]) and (l[bisect_left(l, password)] == password)

然后我意识到我可以改用 index 方法,如下所示:

import sys

script, password, pwlist = sys.argv
password = password+"\r\n"

l=[line for line in open(pwlist)] #Note we don't need to sort this time

#Catch the "not in list" exception
try:
print (password <= l[-1]) and (l[l.index(password)] == password)
except ValueError:
print "False"

我的第二个版本大大减少了执行时间,因为列表不需要排序。我以正确的方式处理这个问题吗? index() 方法如何工作?如果它适用于未排序的列表,那么它肯定不会进行二进制搜索。对此有任何建议,我们将不胜感激。

最佳答案

是的,在第一个示例中,您首先要自己设计一个算法,即二分搜索

在第二个示例中,您只需使用 python 内置的 list.index() 函数。

第二种方法更快,因为排序列表的成本:O(N*log(N)) 比线性搜索的成本数组:O(N)

考虑一下:如果您必须检查多个密码,最好对排序列表进行一次排序和存储,然后在排序后的列表上使用二进制搜索。

关于python - 查找列表中元素的索引。二分查找还是使用索引函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32278255/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com