two-way for `str.rfind`
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Feature or enhancement
Proposal:
After closing with: https://github.com/python/cpython/pull/120025#issuecomment-5281829097
I appreciate that str.rfind is much less frequently used than str.find. But as can be seen it the PR above, it is fairly easy to make two_way bi-directional to handle both. I concluded that for standard track Horspool algorithm the cost of bi-directional logic is best avoided - those methods are fairly short and simple. However, two-way is a plausible candidate I think. Having separate functions for both direction would mean very large code duplications and I think paying a small perf cost to keep single logic for both might be a fairly good deal.
I think it would be good to do it - single string search is one of the most important low level algorithms - having this space clean and complete is I think a good thing -- it would give peace of mind for developers and predictable behaviour for users, and library developers who make heavy use of string search, allowing to derive new algorithms that work in both directions without performance surprises when running in reverse.
There is a workaround of course:
idx = str[::-1].find(sub[::-1])
if idx != -1:
idx = len(str) - len(sub) - idx
However, for small problem sizes this is a non-trivial overhead + double memory.
So, what are the thoughts of others?
Is adapting two-way search to serve str.rfind (eliminating its O(n^2) worst case) desirable/worthwhile?
cc @methane @rhettinger @serhiy-storchaka @vstinner
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从链接的 pull request 中讨论的 str.rfind 入口点和现有 two_way 搜索逻辑开始。比较正向搜索和反向搜索的要求,然后评估双向处理是否可以在不产生不可接受的性能成本或重复函数的情况下,避免 str.rfind 的 O(n^2) 最坏情况。设计达成一致,且其行为和权衡经过验证后,即视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- performance
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 冷清
- 描述清晰度
- 需要澄清
- 新手友好度
- 35/100