python - 括号的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')
解决方案
count
为 0 并且永远不会改变。因此,open_count
如果字符串中没有,则将是未定义(
的,或者它将是 1 但没有别的。对close_count
.
在进行比较时,它会提高 aNameError
或将 1 与 1 进行比较。
恕我直言,代码在许多方面可能要简单得多。
- 无需计算打开和关闭括号。只是增加和减少
count
。 - 查看字符串中的字符,而不是通过索引。当您提前知道迭代次数时使用 for 循环(这里就是这种情况)。如果之前不知道迭代次数,请使用 while 循环。
- 去掉代码中多余的括号
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')
如果您想检查诸如)(
.
推荐阅读
- git - git apply stash 没有索引号
- javascript - Javascript Grammer:如何为对象数组分配正确的值
- javascript - 使用 interSectionObserver 检查元素是否存在
- pandas - 熊猫:比较两个日期,如果两个日期都是日期,那么日期 - 日期 = 天
- python - 基于key:value匹配python修改列表项
- xamarin - 如何防止从“我的 iPhone”文件夹中共享文件
- typescript - 请确保索引 [0] 处的参数 ContactRepository 在 RootTestModule 上下文中可用
- python - `return FileResponse(file_path)`后如何删除文件
- python - 无法写入 JSON 文件
- python - 层 Python 数字总和