简体   繁体   English

Sympy 突然无法识别 varialbe

[英]Sympy suddenly won't recognize varialbe

Last night I wrote a bit of code which ran just fine.昨晚我写了一些运行良好的代码。 Today it won't:今天它不会:

sigma = symbols('x1:4')
D = [1]
for d in D:
    for s in sigma:
        D.append(s*d)
    if len(D) > 20:
        break
print(D)
print(D[19].subs([(x1,4),(x2,2),(x3,3)]))

This, and, in fact anything I write defining symbols xi (ia natural number) returns an error.这个,事实上,我写的任何定义符号 xi(ia 自然数)的东西都会返回一个错误。 For the code above specifically, I get:对于上面的代码,我得到:

>>> for d in D:
...     for s in sigma:
...         D.append(s*d)
...     if len(D) > 20:
...         break
... 
>>> print(D)
[1, x1, x2, x3, x1**2, x1*x2, x1*x3, x1*x2, x2**2, x2*x3, x1*x3, x2*x3, x3**2, x1**3, x1**2*x2, x1**2*x3, x1**2*x2, x1*x2**2, x1*x2*x3, x1**2*x3, x1*x2*x3, x1*x3**2]
>>> print(D[19].subs([(x1,4),(x2,2),(x3,3)]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x1' is not defined

Defining variable names without the 'subscript' works fine.定义没有“下标”的变量名工作正常。 I'm on Ubuntu 19.04 and Visual Studio Code, which, and this is the only thing I can think of, I updated last night.我在 Ubuntu 19.04 和 Visual Studio Code 上,这是我唯一能想到的,我昨晚更新了。

Python thinks you're trying to access a variable called x1, x2, or x3, when instead, you want to tell the subs function to replace instances of "x1" in your expression with 4. Python 认为您正在尝试访问名为 x1、x2 或 x3 的变量,而实际上您想告诉 subs 函数将表达式中“x1”的实例替换为 4。

To fix this, wrap them in quotes to make them a string (explicit is better than implicit):要解决此问题,请将它们用引号括起来以使其成为字符串(显式优于隐式):

print(D[19].subs([("x1",4),("x2",2),("x3",3)]))
>>> 48

Otherwise, you're left with the ambiguity of if you want to replace instances of the string "x1" or if you have a string variable defined somewhere in your code called x1 and want to replace the value x1 in your expression (which is what python thinks you are trying to do).否则,如果您想替换字符串“x1”的实例,或者如果您在代码中的某处定义了一个名为x1的字符串变量并且想要替换表达式中的值x1 (这就是python 认为您正在尝试这样做)。

What you might've had yesterday (maybe you were working in a jupyter notebook or interactive shell), is somewhere in your code you had:您昨天可能拥有的(也许您在 jupyter notebook 或交互式 shell 中工作)是您代码中的某个地方:

x1,x2,x3 = symbols('x1:4')

Which is the same as:这与以下内容相同:

x1 = 'x1'
x2 = 'x2'
x3 = 'x3'

and would explain why your code worked yesterday.并会解释为什么你的代码昨天有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM