簡體   English   中英

括號的while循環程序

[英]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 進行比較。

恕我直言,代碼在許多方面可能要簡單得多。

  1. 無需計算打開和關閉括號。 只是增加和減少count
  2. 通過索引查看字符串中的字符,而不是 go。 當您提前知道迭代次數時使用 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')

如果您想檢查)(之類的文本,代碼可能仍然會失敗。

使用一個計數器,初始化為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM