寻找通过python实现它的不同方法

时间:2019-12-25 21:14:54

标签: python

  • 编写一个简单的解释器,该解释器可以理解“ +”,“-”和“ *”操作。
  • 使用命令/参数对从value的初始值开始按顺序应用操作。
  • 如果遇到未知命令,请返回-1。

示例:

  • interpret(1, ["+"], [1])→2
  • interpret(4, ["-"], [2])→2
  • interpret(1, ["+", "*"], [1, 3])→6
def len_n(val, command, args):

  if command == '+' :
    return val + args
  elif command == '-':
    return val - args
  elif command == '*':
    return val * args
  else:
    return -1

def interpret(val, command, args):

  count = len(command)

  for i in range(count) :
    val = len_n(val,command[i],args[i])

  return val
*****************

************************
  final = len_n(val,command[0],args[0])
  del command[0]
  del args[0]
  if command[0:]:
    final = interpret(final, command, args)

  return final
****************

我通过以上2种方法尝试过也都有效!还有哪些其他方法可以实施?谢谢,

1 个答案:

答案 0 :(得分:0)

解决这类算术解析问题的一种好方法是Dijkstras shunting-yard algorithm,它将以中缀表示法(如(3 + 1) * 6)编写的算术表达式转换为Reverse polish notation(如3 1 + 6 *),每个运算符都放在其运算符之后,而不是在它们之间。

反向抛光符号使计算结果更加容易:

# Calculates the result of a given arithmetic expression only containing numbers
# and +, * when given in reverse polish notation

outputStack = []

def addNumber(number):
    outputStack.append(number)

def addOperator(operator):
    result = operator(outputStack.pop(), outputStack.pop())
    outputStack.append(result)

def addOperatorByChar(operatorChar):
    if (operatorChar == '+'):
        addOperator(lambda x, y: x + y)
    if (operatorChar == '*'):
        addOperator(lambda x, y: x * y)
    #unknwon operator, don't do anything

#test code:
addNumber(3)
addNumber(1)
addOperatorByChar("+")
addNumber(6)
addOperatorByChar("*")

print(outputStack[0])   #should be 24 in this example
print(len(outputStack)) #should be one after correct arithmetic expression