对于循环计算不正确

时间:2015-10-22 11:42:33

标签: python for-loop operators python-3.4

因此,对于以下以反向波兰表示法(RPN)计算数学表达式的代码,对于某些输入,最终计算(输出)似乎不正确。

示例输入:

  • [10,10," add",2" divide"]相当于(10 + 10)/ 2并且应该产生10
  • 的输出
  • [3,1,"乘以",2"除以"]相当于(3 * 1)/ 2并且应该产生1.5
  • 的输出

(所有输出应为浮点数)

def evalSimpleEqn(eqn):
    result = []
    for x in eqn:
        if x == "add":
            result.append( result.pop() + result.pop() )
        elif x == "subtract":
            result.append( result.pop() - result.pop())
        elif x == "multiply":
            result.append( result.pop() * result.pop() )
        elif x == "divide":
             y = ((result.pop()))
             z = (result.pop())
             result.append( z/y )
        else:
              result.append(x)

    return (result[-1])

具体来说,当我输入时: [12,8,"减去",2,"划分",4,"划分",1,"添加"]

该函数返回0.5而不是1.5。我该如何解决?感谢您的任何帮助!

3 个答案:

答案 0 :(得分:3)

问题出在减法操作中:操作数在您的实现中互换。你必须像对待师一样对待它。对于加法和乘法,顺序无关紧要。

def rpn_eval(s):
    result = []
    for x in s:
        print(result)
        if x == "add":
            result.append(result.pop() + result.pop())
        elif x == "subtract":
            y = result.pop()
            x = result.pop()
            result.append(x - y)
        elif x == "multiply":
            result.append(result.pop() * result.pop())
        elif x == "divide":
            y = result.pop()
            z = result.pop()
            result.append(z / y)
        else:
            result.append(x)

    return result[-1]

并且将您的姓名taken称为eval可能不是一个好主意。

答案 1 :(得分:1)

只是为了好玩,另一种方法是更容易扩展:

#!/usr/bin/env python

"""Example code showing how to build an easily extensible RPN calculator"""

def rpn_eval(expression):
    """Calculates the passed expression list and returns the result"""
    result = []
    ops = {"add":float.__radd__,
           "subtract":float.__rsub__,
           "multiply":float.__rmul__,
           "divide":float.__rtruediv__
          }
    for arg in expression:
        result.append(arg if arg not in ops
                      else ops[arg](result.pop().__float__(), result.pop()))
    return result[-1]

def main():
    """main function"""
    tests = [
        [10, [10, 10, "add", 2, "divide"]],
        [1.5, [3, 1, "multiply", 2, "divide"]],
        [1.5, [12, 8, "subtract", 2, "divide", 4, "divide", 1, "add"]]
        ]

    for ans, expr in tests:
        calc_ans = rpn_eval(expr)
        print '{} == {}?  {}'.format(ans, calc_ans, ans == calc_ans)

if __name__ == "__main__":
    main()

答案 2 :(得分:0)

主要代码中的两项更改

def evalSimpleEqn(eqn):
    result = []
    for x in eqn:
        if x == "add":
            result.append( result.pop() + result.pop() )
        elif x == "subtract":
            # (1) reorder operands, as pop() extract firstly subtrahend and then minuend 
            result.append( - result.pop() + result.pop())
        elif x == "multiply":
            result.append( result.pop() * result.pop() )
        elif x == "divide":
             y = ((result.pop()))
             z = (result.pop())
             # (2) add 1.* to convert result to float  
             result.append( 1.* z/y )
        else:
              result.append(x)
    return (result[-1])