Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if expression contains symbol

Tags:

sympy

I would like to find out programatically if a SymPy expression contains a symbol. E.g., for

import sympy
x = sympy.Symbol('x')
y = sympy.Symbol('y')
a = 4 + x**2 + y
b = 4 + y**2

a contains both x and y, b contains only y.

like image 516
Nico Schlömer Avatar asked Jun 24 '15 14:06

Nico Schlömer


2 Answers

>>> x in a.free_symbols, y in a.free_symbols
(True, True)
>>> x in b.free_symbols, y in b.free_symbols
(False, True)
like image 129
Bjoern Dahlgren Avatar answered Oct 19 '22 02:10

Bjoern Dahlgren


You can also use .atoms(Symbol) to check that. atoms(Symbol) differs from .free_symbols in some cases. free_symbols doesn't return dummy symbols, like integration variables. it's usually what you want, since expressions don't mathematically depend on dummy symbols example:

>>> Integral(f(x), (x, 0, 1)).atoms(Symbol)
set([x])
>>> Integral(f(x), (x, 0, 1)).free_symbols
set([])
like image 45
gxyd Avatar answered Oct 19 '22 03:10

gxyd