python - Python字符串操作,通过找到右括号到左括号来删除内容
问题描述
问题是从左括号'['到右括号']'中删除内容
我设法把它写出来,但由于输出不是问题想要的,我没有通过给我的某些测试用例。
我得到的一个提示是,首先找到首要的右括号']',然后追溯到最新的左括号'[',并删除从首要右括号到最新的左括号的所有内容。
但是,我不知道如何写出来。感谢您的帮助
我的代码如下:
def trial():
b = False
user_input = input("test cases : ")
formatstr = ""
for i in user_input:
if '[' in i:
b = True
elif not b:
formatstr += i
if ']' in i:
b = False
print(formatstr)
trial()
这些是具有所需输出的测试用例。
接下来是我的输出,它失败了一些测试用例
[[bean]abc → [abc
**My Output = abc** `Testcase failed`
[bean]]abc → ]abc
**My Ouput = ]abc** `Testcase passed`
abc[foo][qwerty] → abc
**My Output = abc** `Testcase passed`
abc[qwerty]bean] → abcbean]
**My Output = abcbean]** `Testcase passed`
abc[qwerty[bean] → abc[qwerty
**My Output = abc** `Testcase failed`
bean[abc[qwe]dfg] → bean
**My Output = beandfg]** `Testcase failed`
解决方案
您通常通过实现堆栈来处理嵌套结构。当您遇到 a 时,"["
您将一个项目添加到堆栈中,并且当您从堆栈中遇到 a"]"
时pop()
。否则,您将追加添加到堆栈顶部的项目。在您的示例中,您需要确保添加实际的括号,因为测试似乎需要它们。这可能看起来像:
def trial(user_input):
groups = ['']
for i in user_input:
if i == '[':
groups.append(i)
elif i == ']' and len(groups) > 1:
groups.pop()
else:
groups[-1] += i
return "".join(groups)
assert(trial("[[bean]abc") == "[abc")
assert(trial("[bean]]abc") == "]abc")
assert(trial("abc[foo][qwerty]") == "abc")
assert(trial("abc[qwerty]bean]") == "abcbean]")
assert(trial("abc[qwerty[bean]") == "abc[qwerty")
assert(trial("bean[abc[qwe]dfg]") == "bean")
# all pass
推荐阅读
- php - 在 pdo 登录中添加密码哈希
- python - 循环/递归以处理 Python 中的层次结构
- javascript - 图片 (img) 标签返回 404 和默认图片
- java - Java 泛型:转换列表
列出 - react-router - 反应路由器仅更新网址
- azure-devops - 如何将 Azure DevOps 构建工件复制到同一管道中的 Docker 映像构建?
- amazon-web-services - 粘贴 Spark Scala 脚本以检查 S3 中是否存在文件?
- maven - 从现有源对模块运行 mvn 命令
- jquery - 如何使用列的类名来设置默认列排序?
- javascript - setInterval 内的 api 命中两次