2017-03-23 7 views
4

私は以下の 'ツリーサイザー'を実装しましたが、特定の条件下で失敗しました。例4はサイズ4を返すときにサイズ2を返します。私はこれを何度も書きましたが、役に立たない、それは失敗し続けます。事前のおかげでRPNツリーサイズを取得

JC

def getRPNdepth(expression): 
    treesize=0 
    maxtreesize=treesize 
    mintreesize=treesize 
    tmpexp=expression 
    tmpfmla = [1 if n[0] == 'x' else n for n in tmpexp] 
    print(tmpfmla) 
    try: 
     stack = [] 
     for val in tmpfmla: 
      if val in ['-', '+', '*', '/']: 

       op1 = stack.pop() 
       op2 = stack.pop() 
       if val == '-': result = op2 - op1 
       if val == '+': result = op2 + op1 
       if val == '*': result = op2 * op1 
       if val == '/': 
        if op1 == 0: 
         result = 1 
        else: 
         result = op2/op1 
       stack.append(result) 
       treesize=treesize+1 
      else: 

       stack.append(float(val)) 
       treesize = treesize - 1 

      if treesize>maxtreesize: 
       maxtreesize=treesize 
      if treesize<mintreesize: 
       mintreesize=treesize 
     return abs(mintreesize) 
    except: 
     print('error validate rpn>' + str(expression)) 
     return 0 



xxxx = ['x6', 'x7', '+', 'x7', '+', 'x7', '+', 'x7', '+'] 
print(getRPNdepth(xxxx)) 

例のカップル: [ '1'、 '1'、 '+'、 '1'、 '1'、 '+'、 '+'] ['1'、 '1'、 '1'、 '+'、 '+'] はどちらも3の結果を返します。 は、3のときに3を返します。4

まったく、私は知る必要がありますその文字列表現からのRPNの深さ。

+0

「木のサイズは何ですか?一般的には、mintreesizeとmaxtreesizeを同じ値に初期化しないでください。 – Jett

+0

私がツリーサイズと呼ぶものはツリーの深さです。 –

+0

mittreesizeとmaxtreesizeは同じ値に初期化されていますが、ツリーはまだ '測定'されていないため、 –

答えて

3

ツリーの深さを計算する式を評価するに似ていますが、事業者は、得られた値の結果の深さを代わりに計算する:

def getRPNdepth(expression): 
    stack = [] 
    for val in expression: 
     if val in ['-', '+', '*', '/']: 
      stack.append(max(stack.pop(),stack.pop())+1) 
     else: 
      stack.append(1) 
    return stack.pop() 
+0

あなたは50ポイントに値します! –

0

まあ、ちょうどちょっと騙されて同じ目標を達成するためにコンバータを入れ替えるために私のRPMを使用しました、誰かが必要ならばここに投稿します。

def getRPNdepth(expression): 
    tmpexp = expression 
    tmpfmla = [1 if n[0] == 'x' else n for n in tmpexp] 
    stack = [] 
    for val in tmpfmla: 
     if val!=' ': 
      if val in ['-', '+', '*', '/']: 
       op1 = stack.pop() 
       op2 = stack.pop() 
       stack.append('(' + str(op1) + str(val) + str(op2) + ')') 
      else: 
       stack.append(str(val)) 

    openparentesiscount=0 
    maxopenparentesiscount = 0 

    onlyparentesis='' 
    for c in stack[0]: 
     if c in ['(', ')']: 
      onlyparentesis=onlyparentesis+c 
      if c=='(': 
       openparentesiscount=openparentesiscount+1 
      else: 
       openparentesiscount = openparentesiscount - 1 
     if openparentesiscount>maxopenparentesiscount: 
      maxopenparentesiscount=openparentesiscount 

    return maxopenparentesiscount 

ありがとうございます!