Using sympy , you can create a class for each of your equations. Create equation symbols with Ο, Ο = sp.symbols('Ο Ο') , etc., by the equation itself, and then use the f() function to do the rest:
import sympy as sp # Create all symbols. P, V, n, R, T = sp.symbols('PV n R T') # Create all equations IDEAL_GAS_EQUATION = P*V - n*R*T def f(x, values_dct, eq_lst): """ Solves equations in eq_lst for x, substitutes values from values_dct, and returns value of x. :param x: Sympy symbol :param values_dct: Dict with sympy symbols as keys, and numbers as values. """ lst = [] lst += eq_lst for i, j in values_dct.items(): lst.append(sp.Eq(i, j)) try: return sp.solve(lst)[0][x] except IndexError: print('This equation has no solutions.')
To try this ...:
vals = {P: 2, n: 3, R: 1, T:4} r = f(V, values_dct=vals, eq_lst=[IDEAL_GAS_EQUATION, ]) print(r)
If you do not provide enough parameters via values_dct , you will get a result like 3*T/2 , checking its type() , you will get <class 'sympy.core.mul.Mul'> .
If you provide all the parameters that you get as a result of 6 , and its type is <class 'sympy.core.numbers.Integer'> , you can throw exceptions or whatever you need. You can also convert it to int using int() (this will throw an error if instead of 6 you have 3*T/2 so you can check it the same way).
Alternatively, you can simply check if the None values ββin values_dct greater than 1.
To combine several equations, for example PV=nRT and P=2m , you can create an additional symbol m , like the previous symbols, and assign 2m new equation name MY_EQ_2 , and then insert it into the eq_lst function:
m = sp.symbols('m') MY_EQ_2 = P - 2 * m vals = {n: 3, R: 1, T:4} r = f(V, values_dct=vals, eq_lst=[IDEAL_GAS_EQUATION, MY_EQ_2]) print(r)