Creating a function that takes an equation given as a string and computes it [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-06 16:54:35

using eval can be very dangerous if you accept strings to evaluate from untrusted input. for example Suppose the string being evaluated is "os.system('rm -rf /')" ? It will really start deleting all the files on your computer.

So you can parse it with python's internal compiler :

import compiler
eq="48+6*6/3"
ast= compiler.parse( eq )

>>> compiler.parse( eq )
Module(None, Stmt([Discard(Add((Const(48), Div((Mul((Const(6), Const(6))), Const(3))))))]))
>>>

Also you can use sympy that is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python and does not require any external libraries.

You can use Polish notation. http://en.wikipedia.org/wiki/Polish_notation This is a stack based algorithm for parsing and evaluating data. It is quite simple and widely used.

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