括号匹配python
时间: 2023-11-05 19:59:02 浏览: 133
python-括号匹配
括号匹配是一个常见的问题,可以使用栈来解决。下面是一个用Python实现括号匹配的示例代码:
```python
def is_balanced(expression):
stack = []
opening_brackets = ['(', '[', '{']
closing_brackets = [')', ']', '}']
for char in expression:
if char in opening_brackets:
stack.append(char)
elif char in closing_brackets:
if len(stack) == 0:
return False
top_char = stack.pop()
if opening_brackets.index(top_char) != closing_brackets.index(char):
return False
return len(stack) == 0
# 测试
expression = input("请输入待检测的表达式:")
if is_balanced(expression):
print("括号匹配成功!")
else:
print("括号匹配失败!")
```
请注意,上述代码只能检测括号是否匹配,而不能检测其他符号如方括号、花括号等是否匹配。
阅读全文