pythonsympy

SymPy and dictionary variables


I need to use for SymPy operations a number of variables that depend on other parameters in the code. As I understand, a dictionary is used normally when the number of variables is not known in advance. However, SymPy does not allow to declare dictionary variables (say, d[1][1]) symbols and use them in symbolic operations like deriving expressions with respect to them. What would be a proper solution for this situation?


Solution

  • It's not very clear what you want to do, but is it something like this?

    >>> from sympy import *
    >>> from collections import defaultdict
    

    enter image description here

    You could also use a function (which behaves better wrt differentiation) but it would be accessed as d[1](0) instead of d[1][0]:

    >>> s=numbered_symbols('x',cls=Function)
    >>> d=defaultdict(lambda:next(s))
    >>> (d[0](1) + 2*d[1](1)).diff(d[1](1))
    2