首页 > 解决方案 > 括号的while循环程序

问题描述

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

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

标签: pythonwhile-loop

解决方案


count为 0 并且永远不会改变。因此,open_count如果字符串中没有,则将是未定义(的,或者它将是 1 但没有别的。对close_count.

在进行比较时,它会提高 aNameError或将 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')

如果您想检查诸如)(.


推荐阅读