Symbolic Expressions in python
#symbolic.py
#
#This is a python module to represent symbolic expressions
#
#>>>a = sym("a")
#>>>b = sym("b")
#>>>print eq(a + b, 5 * -b * b* b + 5)
#((a+b)=((((5*-b)*b)*b)+5))
class opp:
"""
Base class for all operators and the symbolc class
"""
def __getattr__(self, attr):
if attr[:2] == "__" and attr[-2:] == "__":
funcname = attr[2:-2]
if funcname in operators:
return lambda *x: operators[funcname](self, *x)
elif funcname[0]=='r' and funcname[1:] in operators:
return lambda x: operators[funcname[1:]](x, self)
raise ("AttributeError: object '%s' has no attribute '%s'" %
(repr(self), attr))
def __coerce__(self, other):
return None
class sym(opp):
"""
Symbols are used as variables in equations
"""
def __init__(self, name):
self.name = name
def __repr__(self):
return "sym("+self.name+")"
def __str__(self):
return self.name
class binopp(opp):
"""
This is base class for defining binary operators
"""
def __init__(self, lhs = None, rhs = None):
self.lhs = lhs
self.rhs = rhs
def __str__(self):
return "("+str(self.lhs)+self.operator+str(self.rhs)+")"
def __repl__(self):
return self.operator+"("+repl(self.lhs)+", "+repl(self.rhs)+")"
class uniopp(opp):
"""
This is the base class for unary operators
"""
def __init__(self, value):
self.value = value
def __str__(self):
return self.operator+str(self.value)
def __repr__(self):
return self.operator+"("+repr(self.value)+")"
#Operator definitions
class eq(binopp): operator = "="
class add(binopp): operator = "+"
class sub(binopp): operator = "-"
class div(binopp): operator = "/"
class mul(binopp): operator = "*"
class neg(uniopp): operator = "-"
operators = {"add":add, "sub":sub, "div":div,"mul":mul, "neg":neg}
0 Comments:
Post a Comment
<< Home