Math Expression Evaluation

前端 未结 6 1176
感情败类
感情败类 2020-11-30 09:22

What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: \"4+3*5\" will output 19

6条回答
  •  旧巷少年郎
    2020-11-30 09:56

    That's what the "eval" function does in Python.

    result = eval(expression)
    

    Beware though it can do a whole lot more, primarily call functions, so to be safe you should make sure it can't access the locals or globals. Also, you can access the builtin methods, including the tricky import so you need to block access to that as well:

    result = eval(expression, {'__builtins__': None}, {})
    

    But that's only if you need security, that is if you allow anybody to type in any expression.

    Of course since you this way block all locla variables from use, then you don't have any variables to use, so to have that you need to pass in just those variables which should be accessed in the dictionaries.

    vars = {'__builtins__': None, 'x': x}
    result = eval(expression, vars, {})
    

    or similar.

提交回复
热议问题