Home > Back-end >  How can I evaluate a math expression given as a list of strings?
How can I evaluate a math expression given as a list of strings?

Time:12-15

I have a list of tokens like this:

tokens = ["6", " ", "8"]
result = calculate(tokens) # ?

And I would like to create a calculate function that would evaluate the result of this expression.

I attempted to do something like:

while has_operator(tokens):
    operator_str, operator_pos = find_next_operator(tokens)
    left = tokens[operator_pos - 1] # Number to the left of operator
    right = tokens[operator_pos   1]                 # to the right
    result = evaluate(left, right, operator_str)     # Eval function
    tokens[operator_pos-1:operator_pos 2] = [result] # Replace back
final_result = int(tokens[0])

# eg: ['2', '*', '3', ' ', '4']
#     ['6', ' ', '4'] 
#     ['10'] 
#     result =  10

At the end, the list would reduce to a single value, the answer.

How would this work when both operators and numbers are stored in the same array?

How would I be able to convert the operator string in a real operator?

CodePudding user response:

One possible solution (that of course might be over engineered) would be converting your input to enter image description here

  • Related