あなたはシンボルや演算子を作成することによってこれを行うことができます\標準のPythonデータモデル(http://docs.python.org/2/reference/datamodel.html)を実装するクラス。その後
class Symbol(object):
def __init__(self, name):
self._name = name
def __str__(self):
return str(self._name)
def __div__(self, other):
return Div(self, other)
def __mul__(self, other):
return Mult(self, other)
def __add__(self, other):
return Add(self, other)
def __sub__(self, other):
return Sub(self, other)
def __rdiv__(self, other):
return Div(other, self)
def __rmul__(self, other):
return Mult(other, self)
def __radd__(self, other):
return Add(other, self)
def __rsub__(self, other):
return Sub(other, self)
class Operation(Symbol):
def __init__(self, a, b, op):
self._a = a
self._b = b
self._op = op
def __str__(self):
return self._op.format(self._a, self._b)
class Add(Operation):
precedence = 0
def __init__(self, a, b):
super(Add, self).__init__(a, b, "{0} + {1}")
class Sub(Operation):
precedence = 0
def __init__(self, a, b):
super(Sub, self).__init__(a, b, "{0} - {1}")
class Mult(Operation):
precedence = 1
def __init__(self, a, b):
if isinstance(a, Operation) and a.precedence < Mult.precedence:
a_form = "({0})"
else:
a_form = "{0}"
if isinstance(b, Operation) and b.precedence < Mult.precedence:
b_form = "({1})"
else:
b_form = "{1}"
super(Mult, self).__init__(a, b, a_form + " " + b_form)
class Div(Operation):
precedence = 1
def __init__(self, a, b):
super(Div, self).__init__(a, b, "\\frac{{{0}}}{{{1}}}")
A = Symbol('A')
B = Symbol('B')
C = Symbol('C')
x = Symbol('x')
:
独自のパーサを書くのショート
>>> print (C - A * x)/(B)
\frac{C - A x}{B}
>>> print (C * (A + B))
C (A + B)
>>> print (C * (A + B + A + B + C + x))
C (A + B + A + B + C + x)
望ましくない出力を与えるコードを提供するかもしれませんか? – alko
@alko私はSageとsympyの例を含めるように編集しました – frnhr