括号的while循环程序

时间:2021-02-08 18:46:24

标签: python while-loop

这是我的新代码。我已经对其进行了调整,但它显示括号始终处于平衡状态。

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')

3 个答案:

答案 0 :(得分:0)

count 是 0 并且永远不会改变。因此,如果字符串中没有 open_count,则 ( 要么是未定义的,要么是 1 但没有别的。 close_count 也一样。

进行比较时,它会引发 NameError 或将 1 与 1 进行比较。

恕我直言,代码在很多方面都可以简单得多。

  1. 无需计算开括号和闭括号。只需增加和减少 count
  2. 查看字符串中的字符,而不是通过索引。当您提前知道迭代次数时,请使用 for 循环(这里就是这种情况)。如果之前不知道迭代次数,请使用 while 循环。
  3. 去掉代码中多余的括号
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)

使用一个计数器,初始化为 0Add 1 为每个 (subtract 1 为每个 )。 如果结果是 zeronever 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)