class EmptyStackException(Exception): pass class Element: def __init__(self, value, next): self.value = value self.next = next class Stack: def __init__(self): self.head = None def stackhead(self): return self.head def push(self, element): self.head = Element(element, self.head) def gethead(self): return self.head.value def pop(self): if self.empty(): raise EmptyStackException result = self.head.value self.head = self.head.next return result def empty(self): return self.head == None stack=Stack() stack.push(1) s="" class Expr(object): __exprs = {} # dict for interning nodes def __new__(cls, *args): s="" stack.push(args[0]) s=s+"\n"+str(args[0]) # Get the canonical form of the node, like a hash key. The # simple technique below works because nodes are constructed # bottom-up, so we know that the contents of args are unique. canonical = (cls, args) # Now see if an equivalent node is already interned. try: Expr.__exprs[canonical] s=s+str(" Using existing %s node." % cls.__name__) except KeyError: s=s+str(" Constructing new %s node." % cls.__name__) Expr.__exprs[canonical] = object.__new__(cls, *args) fout.write(s) return Expr.__exprs[canonical] def __add__(self, r): arg1=stack.pop() arg2=stack.pop() sum1=arg1+arg2 Lit(sum1) #print stack.gethead() return 0 def __sub__(self, r): arg=[] arg1=stack.pop() arg2=stack.pop() sub1=arg1-arg2 Lit(Sub1) #print stack.gethead() return 0 def __mul__(self, r): arg1=stack.pop() arg2=stack.pop() mul1=arg1*arg2 Lit(mul1) #print stack.gethead() return 0 def __div__(self, r): arg1=stack.pop() arg2=stack.pop() div1=arg2/arg1 Lit(div1) #print stack.gethead() return 0 class Atom(Expr): def __init__(self, numOrStr): try: self.v except AttributeError: self.v = numOrStr class Lit(Atom): pass class BinOp(Expr): def __init__(self, left, right): try: self.l # or self.r; whichever except AttributeError: self.l = left; self.r = right class Add(BinOp):pass class Sub(BinOp): pass class Mul(BinOp): pass class Div(BinOp): pass if __name__=='__main__': fout=open('out_18_5.txt','w') (Lit(2)+ Lit(3)*Lit(4))+(Lit(24)/(Lit(3)*Lit(4))) #print count_nodes(Lit(2)+(Lit(3)*Lit(4)))