2016-11-15 3 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 '...'が定義されていません](http://stackoverflow.com/questions/21122540/input-error-nameerror) -name-is-not-defined) –

+0

入力時に '(' – 0aslam0

答えて

0

しかし、あなたは部分的にこのタスクを誤解していると思います。

入力だけでなくカッコ

で構成されていることを、そこに多くのブラケットであってもよいが、これ以上の「)」よりも「(」(と最後に両方のタイプの数が同じでなければならない) そして、私が思うだろうことができますが

だから、あなたは(あなたも、1つのカウンターを持っている可能性が(あなたが行ったように)ループを構築し、

  1. テスト、charはブラケットであるかどうか
  2. ブラケットた場合、その照合カウンターを増やす必要がありますそれらの2つで理解するのがより容易です
  3. 終了カウンターがオープニングよりも小さいかどうかをチェックします(そうでない場合、ループを壊す可能性があり、数学的ではないため)
  4. ループの終了後、ループにエラーがあるかどうかをチェックする必要がありますまたは両方のカウンタが等しくない。どちらの場合も、文字列は「数学的」ではありません。

私はあなたのコードでそれを行うことができますが、私はこれを単独で行うべきだと思います。あなたがすでに行ったこれらの事のほとんどは、あなたが完了したことを理解していなかったように、あなたがやったことと何をしなければならないかのようです。

関連する問題