Search code examples
pythonprintingreturnoperatorseval

How to convert multiple string operators into numbers?


I have been trying to create a calculator in Python using tkinter, but it is not working out. I am trying to use the operator library and the eval function.

import operator

ops = {
    '+' : operator.add,
    '*' : operator.mul,
}


def eval_binary_expr(op1, oper, op2, get_operator_fn=ops.get):
    op1, op2 = int(op1), int(op2)
    return get_operator_fn(oper)(op1, op2)


print(eval_binary_expr(*("1 + 3 * 4".split())))

Please help me. It just does not work for me. I am a beginner, so I am bad at this. Sorry if you think this question was stupid.


Solution

  • Think about this: How many items does the list have, that results from "1 + 3 * 4".split()? How do they line up with the formal parameters of eval_binary_expr?

    One common approach to this type of problem, if you want the usual operator precedence, is the shunting-yard algorithm