gpt4 book ai didi

python - 重复删除出现的子字符串,直到主字符串为空

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:29 24 4
gpt4 key购买 nike

<分区>

所以我有了堆栈和针:

stack = 'lllolollololollllolol'

needle = 'lol'

如果我每次从 stack 中移除一根 needle,按照正确的顺序,stack 可以被清除,所以它最后是空的。例如,每次删除粗体的lol(注意删除后可以进一步创建另一个needle):

lllolollolololll哈哈ol

lllolollolololl哈哈

llolollolololl

llololo哈哈l

哈哈哈哈ol

l哈哈ol

哈哈

清晰

要找到像上面这样的路线,我想到使用 Python 的唯一方法是使用正则表达式 (finditer) 找到 stack 中的所有 needles,并且使用递归探索所有可能的删除组合,以找到可以使 stack 为空的组合。但我知道这根本没有效率。

有没有一种更有效的方法来找到至少一种方法来使用 Python 移除 needle 以清空 stack

我找到了这个主题: Remove occurences of substring recursively但我不确定它是否 100% 适用于我的情况。

谢谢!

下面是我想出的代码(我知道复杂性很差..):

def answer(chunk, word):
if chunk.find(word) != -1:
occ = [m.start() for m in finditer('(?='+word+')', chunk)]
for o in occ:
new = chunk[:o] + chunk[o + len(word):]
answer(new, word)
else:
result.append(chunk)
result.sort()
return chunk
...
#So all the shortest "leftover stack" after the removal are stored in list
#"result". These include empty or non-empty outputs depending on how
#the removal was executed.

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