Evaluating mathematical expression from a string a

2019-09-06 03:38发布

问题:

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)