eval()
s 不起作用,因为 left 和 right 是字符串,而不是表达式。此外,您必须进行大量验证才能使用户输入的内容成为有效的 Python 表达式。考虑一下您可能会得到的一些值:
# The typical person's notation for x-squared isn't valid Python
x^2 + x - 3
# 3x means 3 * x to us, but to python it means nothing
3x + 4
# Some people use % to represent division, but that's a modulo operator to Python
3 % 4x
# Python doesn't understand the distributive property
3(4 - x)
# People might use some functions in a way Python doesn't understand
cos x
# Square brackets are used synonymously with parentheses
x[(x^2 - 5)(x^3 - 5x)]
因此,简而言之,您需要某种引擎将纯文本方程转换为有效的 Python 表达式。这不是一件容易的事,但肯定可以做到。
尽管您的项目非常雄心勃勃,但我认为这是使用 Python 的好方法!如果您想出一种将方程式作为字符串转换为有效 Python 的智能方法,您应该立即分享它,因为科学和数学社区中的很多人都可以使用它。