python - 给定字符串和(列表)单词,返回包含字符串的单词(最优算法)
问题描述
假设我们有一个唯一单词列表和一个子字符串。
我正在寻找一种最佳算法,它返回包含子字符串的单词。
一般应用是:给定一个数据库,使用搜索栏过滤结果。
Python中的一个简单实现:
def search_bar(words, substring):
ret = []
for word in words:
if substring in word:
ret.append(word)
return ret
words = ["abc", "bcd", "thon", "Python"]
substring = "on"
search_bar(words, substring)
这将返回:
["thon", "Python"]
在 timeO(lenght_of_list * complexity_of_in)
中,complexity_of_in在某种程度上取决于子字符串的长度和单个单词的长度。
我要问的是是否有更快的实施。鉴于我们可以将列表预处理为我们想要的任何结构。
只是重定向到问题/答案将是惊人的。
注意:如果这种结构不需要太长时间来添加一个新单词会更好。但主要它不需要能够添加任何东西,因为 Python 示例没有。
另外,我不确定这个问题的标签......
解决方案
也许使用
word.find(substring)
反而
substring in word
并作为变体:
def search_bar(words, substring):
return list(filter(lambda word: word.find(substring)!=-1, words))
推荐阅读
- python - 我试图将抓手添加到现有的 moveit 包中
- java - 如何单击按钮并使用硒选择值?
- powerbi - 尝试访问在 Azure SQL Server 上运行 SQL 查询的已发布 Power BI 报告时出现缺少凭据错误
- flutter - 如何让 openEndDrawer() 响应我的自定义 AppBar 按钮而不是想象的 AppBar 按钮?
- heroku - apt-get update 在 Heroku 中返回 Acquire (30: Read only file system) 错误
- sql - 从查询中删除 / 反斜杠以在 oracle 中获取有效数据
- typescript - 未处理的承诺拒绝:NotAllowedError:用户代理不允许该请求
- c# - Newtonsoft.Json 转换器抛出异常说“无法加载文件或程序集'System.Security.Permissions'”
- python - 欧拉计划问题 52:寻找置换倍数
- node.js - 为什么在 NodeJS 应用中启用 CORS 后仍然出现 CORS 错误?