2017-09-06 5 views
-4

逆ポーランド記法(:RPN)について学びます。Reverse Polish Notation(Python)を使って計算する

RPNを使用して数式を計算します。

私は以下のプログラムを書くことができました。

一見、このコードは適切に機能します。

私はプログラミングコンテストサイト( http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0109 )にこのコードを提出したとき、私は間違った答えを得ました。

私のコードで何が問題になっていますか?

# coding: utf-8 

# Convert String to List 
def String2List(s): 
    L = [] 
    flag = True 
    l = len(s) 
    for i in range(l): 
     if s[i].isdigit() and flag: 
      t = "" 
      j = 0 
      while s[i+j].isdigit(): 
       t += s[i+j] 
       if i+j == l-1: 
        break 
       j += 1 
      L.append(t) 
      flag = False 

     elif not s[i].isdigit(): 
      L.append(s[i]) 
      flag = True 

    return L 


# generate Reverse Polish Notation 
def RPN_list(L): 
    S, L2 = [], [] 
    table = {"*": 1, "/": 1, "+": 0, "-": 0, "(": -1, ")": -1} 
    for i in L: 
     if i.isdigit(): 
      L2.append(i) 
     elif i == "(": 
      S.append(i) 
     elif i == ")": 
      while S[-1] != "(": 
       L2.append(S.pop()) 
      S.pop() 
     else: 
      if len(S) != 0 and (table[S[-1]] >= table[i]): 
       L2.append(S.pop())    
      S.append(i) 

    while len(S) != 0: 
     L2.append(S.pop()) 

    return L2 


# calculate Reverse Polish Notation 
def RPN_cul(L): 
    St = [] 

    for i in L: 
     if i == '+': 
      St.append(int(St.pop()) + int(St.pop())) 
     elif i == '-': 
      St.append(-int(St.pop()) + int(St.pop())) 
     elif i == '*': 
      St.append(int(St.pop()) * int(St.pop())) 
     elif i == '/': 
      a = int(St.pop()) 
      b = float(St.pop()) 
      St.append(b/a) 
     else: 
      St.append(i) 

    return St[0] 


N = int(raw_input()) 

for i in range(N): 
    s = raw_input() 
    L = String2List(s[:-1]) 
    L = RPN_list(L) 

    print int(RPN_cul(L)) 
  • 結果
$ python reverse_polish_notation.py 
2 
4-2*3= 
-2 
4*(8+4+3)= 
60 
+0

def RPN_list(L): ... if len(S) != 0 and (table[S[-1]] >= table[i]): L2.append(S.pop()) S.append(i) ... 
  • 後0 - (2 * 1)+2 = 0 -2 +2 = 0と評価する必要があります。 – Kevin

+0

問題の説明では、すべての値を整数として扱う必要がありますが、丸められていない浮動小数点値を使用しています。 – jasonharper

+0

私はあなたが何を望んでいるか分からない:あなたの例は* infix *ですが、RPMは* postfix *です。 – Prune

答えて

0

次のように私は固定したときに、それを受け入れました。助けてくれてありがとう。前

  • :あなたのプログラムは、 `* 1 0-2 + 2 =` -4与えるが、実際にそれと言う
def RPN_list(L): 
    ... 
     while len(S) != 0 and (table[S[-1]] >= table[i]): 
      L2.append(S.pop())    
     S.append(i) 
    ... 
関連する問題