guimption guimption - 4 years ago 155
Python Question

Why won't sympy take my symbols?

I have symbols defined as follows:

import sympy

class construct(object):
def __init__(self, value):
self.value = value

def __add__(self, symbol):
return construct(self.value+symbol.value)

def __mul__(self,symbol):
return construct(self.value*symbol.value)

a = construct(2)
b = construct(10)


(the above code is runnable). Now, when I try to put them in a
sympy
matrix, it raises an error and I can't figure out why:

import sympy
A= sympy.Matrix([[a],[b]])


....SympifyError: Sympify of expression 'could not parse u'<__main__.construct object at 0x1088a5ad0>'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)


I'm not even using strings here at all, so I'm not sure why it's complaining about a parse error.

Answer Source

I'm not an advanced SymPy user, and I don't quite see what are you trying to accomplish with your construct class.

The <__main__.construct object at 0x1088a5ad0> in the error message is what is returned by the default construct.__str__() method. I notice that once that method is overridden with a method returning string representation of construct.value then anything that uses sympy.sympify() (including sympy.Matrix()) should accept it.

import sympy

class construct(object):

    def __init__(self, value):
        self.value = value

    def __add__(self, symbol): 
        return construct(self.value+symbol.value)

    def __mul__(self,symbol):
        return construct(self.value*symbol.value)

    def __str__(self):
        return str(self.value)

a = construct(2)
b = construct(10)
print(sympy.Matrix([[a],[b]])) # will output 'Matrix([[2], [10]])'

Were I to do this only with SymPy classes, I would use the following:

import sympy
a,b = sympy.symbols('a b')
a = 2
b = 10
print(sympy.Matrix([[a],[b]])) # will output 'Matrix([[2], [10]])'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download