All pastes #2048315 Raw Edit

Miscellany

public python v1 · immutable
#2048315 ·published 2011-04-19 16:26 UTC
rendered paste body
"""file: calc.pylanguage: python3author: R. Canosaauthor: B. Steeleauthor: ### ENTER YOUR NAME HEREdescription: This program uses a stack to calculate the result of             a mathematical expression given in postfix notation.             Operators include '+', '-', '*', and '/'. A postfix             expression has the operator after two operands, for             example,'1 + 2' is represented in postfix as '1 2 +'. """class EmptyListNode(object):    __slots__ = ()class ListNode(object):        __slots__ = ( "data", "next" )        def __init__(self, dataVal, nextVal=EmptyListNode()):                """Initialize the node"""                self.data = dataVal                self.next = nextVal                            def __str__(self):                """Return a string representation of the node"""                return "Node val: "+ str(self.data)            class Stack(object):        __slots__ = ( "top" )                def __init__(self):                self.top = EmptyListNode()        def push(element, stack):        """Add an element to the top of the stack"""        newnode = ListNode(element, stack.top)        stack.top = newnode        def top(stack):        """Access the top element oi the stack without removing it"""        if empty(stack,EmptyListNode): raise IndexError("Stack is empty.")         return stack.top.datadef pop(stack):    """Remove the top element in the stack.       pop : Stack -> None       It is an error if the stack is empty.    """    if isinstance(stack.top,EmptyListNode):        raise IndexError("pop on empty stack")     stack.top = stack.top.next        def empty(stack):        """Is the stack empty?"""        return isinstance(stack.top, EmptyListNode)def evaluate(expression):    """Evaluate and print the postfix expression.       evaluate : String -> None    """    stack = Stack()    for token in expression:        if token.isdigit():            push(int(token), stack)        else:            first = stack.top.data            pop(stack)            second = stack.top.data            pop(stack)            if token is '+': result = first + second            if token is '-': result = first - second            if token is '*': result = first * second            if token is '/': result = second / first            push(result, stack)    if isinstance(stack.top, EmptyListNode): print('Empty Stack')    print( expression + " = " + str( result ) )    returndef test():    print("Test :     ", end='')    evaluate('12+')                 # Answer should be 3    print("Test :     ", end='')    evaluate('54*')                 # Answer should be 20    print("Test :     ", end='')    evaluate('34*64-+')             # Answer should be 14    print("Test :     ", end='')    evaluate('26/31/-')             # Answer should be -2.6666...    print("Test :     ", end='')    evaluate('26/3*')               # Answer should be 1.0    print("Test :     ", end='')    evaluate('26/')                 # Answer should be 0.333    print("Test :     ", end='')    evaluate('572*+2-')             # Answer should be 17    print("Test :     ", end='')    evaluate('62*')                 # Answer should be 12    print("Test :     ", end='')    evaluate('32+')                 # Answer should be 6test()