2016-11-15 61 views
0

我正在處理讀取字符串輸入的代碼,並計算括號(使用任意字符打開和關閉)是否平衡。目的是提示用戶輸入括號中的字符串數量,以便編譯器計算它們的數量和類型(例如,如果它是'('')')。字符串處理 - 確定括號是否平衡

我已經給出提示:

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

Hint2: 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) 

我怎麼會爲了它會工作修改這個?

+0

抱歉,我現在修改了我的問題 –

+0

可能重複[input()error - NameError:name'...'is not defined](http://stackoverflow.com/questions/21122540/input-error-nameerror -name-is-not-defined) –

+0

當你輸入時,給它像'(' – 0aslam0

回答

0

但我認爲你部分誤解了任務。

可以有很多括號,但沒有更多的「)」比「(」(並在年底這兩種類型的數目必須等於) 而且我認爲,該輸入不僅包括括號

所以,你應該建立一個環(像你一樣)和

  1. 測試,焦炭是一個托架或不
  2. 如果一個支架,因此增加了匹配計數器(你甚至可以有一個計數器,但更容易理解其中兩個
  3. 檢查結束計數器是否小於開始值(如果不是,則可以中斷循環,導致它不是數學運算)
  4. 循環結束後,您必須檢查循環結束後是否有錯誤或兩個計數器不相等。在這兩種情況下,字符串都不是「數學」的,否則就是。

我可以在你的代碼中做到這一點,但我認爲,你應該單獨做這件事。你已經完成了大部分這些事情,但看起來你並沒有完全理解,你做了什麼,必須做什麼。