Evaluating mathematical expression from a string and inserting it on stack

你离开我真会死。 提交于 2020-01-17 04:03:17

问题


I'm trying to build an arbitrary precision calculator. I represent numbers in linked lists (one node is a single digit), and I want to store them in a stack. However, I can't seem to figure out how to break the mathematical expression received as a string apart while keeping the right mathematical operations order.

For example, if the inserted expression is 6*8-2+8-8*9/4, I'll represent numbers as linked lists and insert them into a stack, and insert the operators into a different stack, and then I want to pop the arguments for each calculations and push the result again, and so on until I get the final result.

My question is, how can I implement this and still follow the mathematical operations order?


回答1:


you could try using eval?

eval("6*8-2+8-8*9/4")

This would give you 36

EDIT:

If eval isn't feasible, maybe try operator to convert the string operators to mathematical ones:

import operator
operations = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.div,
    '%' : operator.mod,
    '^' : operator.xor
}

Then maybe you could loop through the string and evaluate it that way? (I'll have a think about the looping part now and edit my answer if I get anything good)



来源:https://stackoverflow.com/questions/41445176/evaluating-mathematical-expression-from-a-string-and-inserting-it-on-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!