How can I get a list of the symbols in a sympy expression?

前端 未结 3 1029
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 15:29

For example, if I run

import sympy
x, y, z = sympy.symbols(\'x:z\')
f = sympy.exp(x + y) - sympy.sqrt(z)

is there any method of f

相关标签:
3条回答
  • 2020-12-15 16:02

    Note that JuniorCompressors answer only lists free variables.

    If you have a Sum, a Product, an Integral, or something similar, you may or may not want to additionally know the integration/summation variable using the .variables attribute:

    In [216]: (x, n) = sympy.symbols("x n")
    
    In [217]: f = sympy.Sum(x, (n, 0, 10))
    
    In [218]: f.free_symbols
    Out[218]: {x}
    
    In [219]: f.variables
    Out[219]: [n]
    
    0 讨论(0)
  • 2020-12-15 16:12

    A very useful attribute is atoms

    x, y, z = sympy.symbols('x:z')
    expr1 = sympy.exp(x + y) - sympy.sqrt(z)
    display(expr1.free_symbols)
    display(expr1.atoms(sympy.Symbol))
    
    {                                                                    
    0 讨论(0)
  • 2020-12-15 16:13

    You can use:

    f.free_symbols
    

    which will return a set of all free symbols.

    Example:

    >>> import sympy
    >>> x, y, z = sympy.symbols('x:z')
    >>> f = sympy.exp(x + y) - sympy.sqrt(z)
    >>> f.free_symbols
    set([x, z, y])
    
    0 讨论(0)
提交回复
热议问题