gpt4 book ai didi

python - 使用递归显示字符串中的多个子字符串索引

转载 作者:行者123 更新时间:2023-11-28 19:50:55 25 4
gpt4 key购买 nike

def subStringMatchExact(target, key):

if (target.find(key) == -1):
return []
else:
foundStringAt = [target.find(key)]
target = target[foundStringAt[0] + len(key):]
return foundStringAt + subStringMatchExact(target, key)

string = subStringMatchExact("your code works with wrongly correlated coefficients which incorporates more costs", "co")

print(string)

当前不正确的输出:

[5, 22, 9, 19, 14]

我在计算上一个递归步骤中子字符串的长度时遇到了问题。比如列表的第二个元素应该是 29 而不是 22 len(previousSubstring) + len(key) - 1 + len(currentSubstring)

有什么改进我的代码和/或修复我的错误的想法吗?

最佳答案

快速方法

您不必实现自己的解决方案,它已经完成了!使用 re 模块中的 finditer 函数:

>>> import re
>>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
>>> matches = re.finditer('co', s)
>>> positions = [ match.start() for match in matches ]
>>> positions
[5, 29, 40, 61, 77]

你自己的方式

如果您想自己实现(使用递归),您可以利用 str.find 函数的额外参数。让我们看看 help(str.find) 是怎么说的:

S.find(sub [,start [,end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within s[start:end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

有一个名为 start 的额外参数,它告诉 str.find 从哪里开始搜索子字符串。这正是我们所需要的!

所以,修改你的实现,我们可以得到一个简单、快速、漂亮的解决方案:

def substring_match_exact(pattern, string, where_should_I_start=0):
# Save the result in a variable to avoid doing the same thing twice
pos = string.find(pattern, where_should_I_start)
if pos == -1:
# Not found!
return []
# No need for an else statement
return [pos] + substring_match_exact(pattern, string, pos + len(key))

递归在这里做什么?

  • 您首先要搜索字符串中从位置 0 开始的子字符串。
  • 如果未找到子字符串,则返回一个空列表 []
  • 如果找到子字符串,将返回[pos] 加上子字符串在字符串starting 位置pos + 中出现的所有位置len(键).

使用我们全新的功能

>>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
>>> substring_match_exact('co', s)
[5, 29, 40, 61, 77]

关于python - 使用递归显示字符串中的多个子字符串索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8557292/

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