[英]While loop program for parentheses
這是我的新代碼。 我已經對其進行了調整,但它始終顯示括號平衡。
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 並且永遠不會改變。 因此,如果沒有(
在字符串中或者它將是 1 但沒有其他內容, open_count
將是未定義的。對於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')
如果您想檢查)(
之類的文本,代碼可能仍然會失敗。
使用一個計數器,初始化為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')
通過將所有左括號轉換為 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.