Sympy.solve 返回:“[]”

Sympy.solve returning: " [] "

我正在开发一个接受输入并解决它的程序。我使用了 Sympy。我假设因为这有效:

from sympy import symbols, Eq, solve
x, y = symbols("x y")
eq1 = Eq(5 + x)
eq2 = Eq(5 + y)
sol = solve((eq1, eq2),(x, y))
print(sol)

给出结果:

{x: -5, y: -5}

这也应该有效,因为我正在拆分它,正确格式化代码,并且它有“a”和“z”的输入:

from sympy import symbols, Eq, solve
 
Input = input("Please give the two variables the names 'a' and 'z': ").replace("x", "*").replace("^", "**").upper().split(" = ")
a, z = symbols("a z")
othersol = solve((Input[0], Input[1]),(a, z))
print(othersol)

不过,当给定输入时:

5 + a = 5 + z

它给出了结果:

[]

我想知道为什么它不能求解,为什么它不起作用,以及如何编写一个程序来接受输入并求解给定的方程式。如果需要,我什至会切换我的 Python 库。如果没有,你能给出接受输入并求解方程的代码吗?

有人能做到吗?

谢谢。

当你比较你作为第一个参数给你的 solve 函数的内容时,你会发现这里有什么问题。

在你的工作代码中你这样做:

eq1 = Eq(5 + x)
eq2 = Eq(5 + y)
sol = solve((eq1, eq2),(x, y))

第一个参数是两个 Eq 个对象。

让我们看看您的非工作代码中发生了什么。

>>> Input = input("Please give the two variables the names 'a' and 'z': ").replace("x", "*").replace("^", "**").upper().split(" = ")
Please give the two variables the names 'a' and 'z': a+1 = zx3
>>> Input
['A+1', 'Z*3']
>>> type(Input[0])
<class 'str'>
>>> solve((Input[0], Input[1]),(a, z))
[]

第一个参数是两个字符串的元组。

因此您需要将输入字符串解析为 Eq 对象。然后你就会有工作代码。如果您想让您的用户输入自由文本,这可能是一项具有挑战性的任务。以波兰语表示法或其他一些更结构化的方式输入会更容易解析。

--- 编辑 ----

使用 exec 可能是这样的。我添加了一个功能来稍微保护输入。如果输入中有未知字符,这将失败。

from sympy import symbols, Eq, solve
A, Z = symbols("A Z")

def secure_input(inputstring):
    known_symbols = {" ","A","Z","+","*","**","-"}
    if not all([x in known_symbols or x.isdigit() for x in inputstring]):
        raise Exception("Illegal strings in input %s"%inputstring)
    return inputstring

Input = input("Please give the two variables the names 'a' and 'z': ").replace("x", "*").replace("^", "**").upper().split(" = ")

i1 = secure_input(Input[0])
i2 = secure_input(Input[1])
exec("eq1 = Eq(%s)" % i1)
exec("eq2 = Eq(%s)" % i2)
solve((eq1,eq2),(A, Z))

此外,您使用了小写变量名称,但您对输入字符串说的是 upper()。我也更改了它,现在代码应该可以工作了。

from sympy import symbols, Eq, solve
A, Z = symbols("A Z")

def secure_input(inputstring):
    known_symbols = {" ","A","Z","+","*","**","-"}
    if not all([x in known_symbols or x.isdigit() for x in inputstring]):
        raise Exception("Illegal strings in input %s"%inputstring)
    return inputstring

Input = input("Please give the two variables the names 'a' and 'z': ").replace("x", "*").replace("^", "**").upper().split(" = ")

i1 = secure_input(Input[0])
i2 = secure_input(Input[1])
exec("eq1 = Eq(%s)" % i1)
exec("eq2 = Eq(%s)" % i2)
A = solve((eq1,eq2),A)
Z = solve((eq1,eq2),Z)
print(str(A).replace("{","").replace("}", ""))
print(str(Z).replace("{","").replace("}", ""))