使用反向波兰表示法(Python)计算

时间:2017-09-06 14:39:33

标签: python algorithm python-2.7

我了解反向波兰表示法(:RPN)。

我想用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

2 个答案:

答案 0 :(得分:0)

当我修改如下时,它被接受了。谢谢你的帮助。

  • 之前:
def RPN_list(L):
    ...  
        if len(S) != 0 and (table[S[-1]] >= table[i]):
            L2.append(S.pop())            
        S.append(i)
    ...
  • 后:
def RPN_list(L):
    ...  
        while len(S) != 0 and (table[S[-1]] >= table[i]):
            L2.append(S.pop())            
        S.append(i)
    ...

答案 1 :(得分:0)

polish_str="123*+4-"
#scan from left to right once you got the operator make the operation save the     result again perform the operation
#result=3

polish_list=[]
for i in polish_str:
   polish_list.append(i)

print(polish_list)

####
temp=[]
operator=['*',"+","/","-"]

def operation(o,a,b):
    if o=="+":
        result=a+b
    if o=="-":
        result=a-b
    if o=="*":
        result=a*b
    if o=="/":
        result=a/b
    return result

for i,v in enumerate(polish_list):
    if v in operator:
        print(temp)
        leng=len(temp)
        arg1=temp.pop()
        print("arg1==>",arg1)
        arg2=temp.pop()
        print("arg2==>",arg2)
        result=operation(v,arg1,arg2)
        print("result==>",result)
        temp.append(result)
        print("temp in iteration==>",temp)
    else:
        temp.append(i)


print("***final temp***",temp)