Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy. How to check input is numeric, sympy expression and if so if a symbol included in the expression?

I want to code some function that takes 1 input. The input could be numeric (integer, float, Sympy constant like sympy.pi or expression evaluated as real number like sympy.sin(5)), or could be a sympy expression (like x**2-2*y+5.

What I need is to determine:

  1. Is the input is numeric (has no symbols)?
  2. If the input is expression, does a specific variable exist?

I have tried .free_symbols and it fails if the input is integer and throws exception. Also str(input).isnumeric fails if the input is sympy.sin(5).

like image 223
Mohamed Mostafa Avatar asked Nov 15 '25 09:11

Mohamed Mostafa


1 Answers

There is a function in SymPy called sympify whose purpose is to turn non-SymPy objects into SymPy expressions e.g. an int becomes a SymPy Integer etc. If you sympify the input then you can use free_symbols:

In [6]: def inspect(expr):
   ...:     expr = sympify(expr)
   ...:     symbols = expr.free_symbols
   ...:     if not symbols:
   ...:         print(expr, 'has no symbols')
   ...:     else:
   ...:         print(expr, 'has these symbols:', ', '.join(map(str, symbols)))
   ...: 

In [7]: inspect(1)
1 has no symbols

In [8]: inspect(pi)
pi has no symbols

In [9]: inspect(x+y)
x + y has these symbols: y, x
like image 132
Oscar Benjamin Avatar answered Nov 17 '25 06:11

Oscar Benjamin