第20讲 动动手问题
请各位大佬帮我看看我的代码{:10_266:}为啥运行不了
我觉得逻辑上应该没问题诶
题目:请编写一个程序,判断给定的字符串 s 中括号的写法是否合法。
条件:
字符串仅包含 '('、')'、'['、']'、'{'、'}' 这三对括号的组合
左右括号必须成对编写,比如 "()" 是合法的,"(" 则是非法的
左右括号必须以正确的顺序闭合,比如 "{()}" 是合法的,"{(})" 则是非法的
我写的代码:
s = input("请输入测试字符串:")
list1 =[]
list2 =[]
for c in s:
if c == '(' or c== '{' or c == '[':
list1.append(c)
else:
list2.insert(0,c)
a = len(list1)
b = len(list2)
if a == b:
for i in range(0,a):
if list1 == '(' and list2 == ')':
continue
elif list1 == '{' and list2 == '}':
continue
elif list1 == '[' and list2 == ']':
continue
else:
print("不合法")
i = -1
break
if i == a:
print("合法")
else:
print("不合法")
我猜是因为列表超出索印问题,应该使用 try 方法
本帖最后由 代码小白liu 于 2022-4-17 10:43 编辑
s = input("请输入测试字符串:")
list1 =[]
list2 =[]
for c in s:
if c == '(' or c== '{' or c == '[':
list1.append(c)
else:
list2.insert(0,c)
a = len(list1)
b = len(list2)
if a == b:
for i in range(0, a):
if list1 == '(' and list2 == ')':
continue
elif list1 == '{' and list2 == '}':
continue
elif list1 == '[' and list2 == ']':
continue
else:
print("不合法")
break
else:
print("合法")
else:
print("不合法")
修改了下代码能正常运行了,但是这个思路是只用于只有一种括号,如果是多种括号或者是嵌套的 就是不适用了,[{}] list1是不等于list2的 代码小白liu 发表于 2022-4-17 09:45
修改了下代码能正常运行了,但是这个思路是只用于只有一种括号,如果是多种括号或者是嵌套的 就是不 ...
为什么捏,一个已经是把后进去的放在前面了,另一个是普通的列表,两个list【0】不是应该合法的么
比如说{【】}
list1 录入进去是{【
list2 录入进去是} 】
不是很能理解为什么嵌套就无法运行了 KatouMegumiTyan 发表于 2022-4-17 11:35
为什么捏,一个已经是把后进去的放在前面了,另一个是普通的列表,两个list【0】不是应该合法的么
比如 ...
嵌套可以,[]{}这种不行
页:
[1]