你如何替代 sympy 中的解决方案?

How do you substitute into solutions in sympy?

考虑这个简单的 MWE:

from sympy.solvers.diophantine import diophantine
from sympy import symbols
x, y, z = symbols("x, y, z", integer=True)
diophantine(x*(2*x + 3*y - z))

这输出:

[(t_0, t_1, 2*t_0 + 3*t_1), (0, n1, n2)]

If I want to create instances of these solutions I would like, for example, to able to substitute integer values into t_0 and t_1. How can you do that?

我试过了,例如

diof = diophantine(x*(2*x + 3*y - z))
list(diof)[0][0].subs(t_0, 0)

但这给出了

NameError: name 't_0' is not defined

t_0 未定义为 Python 变量。您可以通过几种不同的方式创建 Python 变量:

from sympy import symbols
t_0 = symbols("t_0")

或者,您可以将 SymPy 计算生成的符号捕获到 Python 变量中。这是一种方法:

diofl = list(diof) # Assuming that diof is as you had defined it.

t_0 = diofl[1][0] # Presuming that this is the part of diofl
                  # that contains the correct symbol. Print 
                  # diofl[1][0] to be sure!

之后,您可以使用 t_0 作为 subs() 方法的参数。