This was written as an underhanded solution to an problem in an online programming challenge (http://www.spoj.pl) that required converting simple arithmetic expressions from infix to postfix form. I thought the solution was pretty neat, and I suspect the general technique may be useful for other problems so i'm including it here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import string
def make_transformer(op):
def transform(self, other):
return rpn_transformer(self.expr + other.expr + (op,))
return transform
class rpn_transformer:
__slots__ = ('expr',)
def __init__(self, expr):
self.expr = expr
__mul__ = make_transformer('*')
__div__ = make_transformer('/')
__add__ = make_transformer('+')
__sub__ = make_transformer('-')
names = dict((c, rpn_transformer((c,))) for c in string.ascii_lowercase)
to_postfix = lambda s: ' '.join(eval(s, names).expr)
# example
assert to_postfix('(a+b)/(c+d+e*f)-h') == 'a b + c d + e f * + / h -'
|
Tags: programs