这是我的新代码。我已经对其进行了调整,但它显示括号始终处于平衡状态。
parentheses_string = input('Enter string:\n')
i = 0
count = 0
while i<len(parentheses_string):
if (parentheses_string[i] == '('):
open_count = count+1
if (parentheses_string[i] == ')'):
close_count = count+1
i = i+1
if open_count==close_count:
print('Parentheses balanced')
else:
print('Parentheses unbalanced')
答案 0 :(得分:0)
count
是 0 并且永远不会改变。因此,如果字符串中没有 open_count
,则 (
要么是未定义的,要么是 1 但没有别的。 close_count
也一样。
进行比较时,它会引发 NameError
或将 1 与 1 进行比较。
恕我直言,代码在很多方面都可以简单得多。
count
。parentheses_string = input('Enter string:\n')
count = 0
for char in parentheses_string:
if char == "(":
count += 1
if char == ")":
count -= 1
if count == 0:
print('Parentheses balanced')
else:
print('Parentheses unbalanced')
如果您想检查 )(
之类的文本,代码可能仍会失败。
答案 1 :(得分:0)
使用一个计数器,初始化为 0
。 Add 1
为每个 (
,subtract 1
为每个 )
。
如果结果是 zero
和 never went negative
,则括号是平衡的。
def check_balance(string):
"""return 0 if parentheses are balanced."""
balance = 0
for char in string:
if char in "()":
if char == "(":
balance += 1
else:
balance -= 1
if balance < 0:
break # too much ')'
return balance
if check_balance(string):
print('unbalanced')
else:
print('balanced')
答案 2 :(得分:0)
通过将所有左括号转换为 1 并将右括号转换为 -1,您可以使用这些映射值的累积总和来执行验证。如果累积水平从未低于 0 且最终总和为零,则括号将被平衡:
from itertools import accumulate
def balanced(S):
levels = [(c=="(")-(c==")") for c in S]
return sum(levels)==0 and -1 not in accumulate(levels)