【发布时间】:2015-02-03 17:16:53
【问题描述】:
我有两个列表,一个是单词,另一个是字符组合。仅返回与列表中任何内容都不匹配的组合的最快方法是什么?
我已尝试使其尽可能精简,但是当它使用 3 个字符进行组合时仍然很慢(4 个字符最多需要 290 秒,甚至不会尝试 5 个)
这是一些示例代码,目前我正在将所有单词转换为一个列表,然后在字符串中搜索每个列表值。
#Sample of stuff
allCombinations = ["a","aa","ab","ac","ad"]
allWords = ["testing", "accurate" ]
#Do the calculations
allWordsJoined = ",".join( allWords )
invalidCombinations = set( i for i in allCombinations if i not in allWordsJoined )
print invalidCombinations
#Result: set(['aa', 'ab', 'ad'])
我只是好奇是否有更好的方法来使用集合来做到这一点?用 3 个字母的组合,有 18278 个要搜索的列表项,对于 4 个字母,最多可以搜索到 475254 个,所以目前我的方法还不够快,尤其是当单词列表字符串大约 100 万个字符时。
Set.intersection 如果您需要整个字符串,这似乎是一个非常有用的方法,所以肯定有类似的东西来搜索子字符串。
【问题讨论】: