[Tutor] A little math and Python: rpn
Gregor Lingl
glingl@aon.at
Thu, 22 Aug 2002 03:07:31 +0200
... or would you prefer this approach?
class RPN_Tree:
def __init__(self, rpnlist):
if len(rpnlist) == 1:
self.node = rpnlist[0]
self.left = None
self.right = None
else:
self.node = rpnlist[-1]
if rpnlist[-2] in ["+","-","*","/"]:
self.left = RPN_Tree(rpnlist[0:1])
self.right = RPN_Tree(rpnlist[1:-1])
else:
self.left = RPN_Tree(rpnlist[:-2])
self.right = RPN_Tree(rpnlist[-2:-1])
def evalTree(rpntree):
if rpntree.node not in ["+","-","*","/"]:
return rpntree.node
else:
return str(eval(evalTree(rpntree.left) + rpntree.node +
evalTree(rpntree.right)))
def rpn(st):
return evalTree(RPN_Tree(st.split()))
Gregor