我正在處理讀取字符串輸入的代碼,並計算括號(使用任意字符打開和關閉)是否平衡。目的是提示用戶輸入括號中的字符串數量,以便編譯器計算它們的數量和類型(例如,如果它是'('
或')'
)。字符串處理 - 確定括號是否平衡
我已經給出提示:
Hint1: introduce two counters initialized to zero in the beginning. Then explore the symbols of the string in a loop. For the current symbol increment the
left
counter by 1 if the symbol is'('
, otherwise, increment by 1 the `right' counterHint2: call a string math-like if the brackets occur like in a mathematical formula. For instance, the strings
'()'
,'(())()'
,'(()())'
are balanced, while the strings'))(())(('
and'())(()'
are not.
我的代碼現在看起來像這樣:
lefts =str(input("Please enter a left parenthesis: "))
rights =str(input("Please enter a right parenthesis: "))
#token parsing requires paying attention to the order of the parenthesis
def ptest(test): #testing with counters
lefts = 0
rights = 0
balance = 0 #additional counter that will help us determine the amount of strings and their relation to each other
for c in test:
if c == '(':
balance += 1
lefts += 1
elif c == ')':
balance -= 1
rights += 1
print ('testing "'+test+'"')
print ('lefts='+str(lefts)+' rights='+str(rights))
#if there will b a balance between the strings/parenthesis, they will possibly be balanced
if balance == 0: print 'same number of open/close, possibly balanced'
else: print 'different number of open/close, definitely not balanced'
ptest(test1)
ptest(test2)
我怎麼會爲了它會工作修改這個?
抱歉,我現在修改了我的問題 –
可能重複[input()error - NameError:name'...'is not defined](http://stackoverflow.com/questions/21122540/input-error-nameerror -name-is-not-defined) –
當你輸入時,給它像'(' – 0aslam0