faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 3 people (100%) answered Yes
Recently 2 of 2 people (100%) answered Yes

Entry

Stack class

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 258, Python Snippet Support Team


"""
Packages: new_datatypes
"""
# stack.py
StackError = 'StackError'
class Stack:
    """A generic Stack class.""" 
    def __init__(self, something=None):
        if type(something) == type([]):
            self._data = []
            for item in something:
                self._data.append(item)
        elif isinstance(something, Stack):
            # copy constructor
            self._data = []
            for x in something._data:
                self._data.append(x)
        elif something is None:
            self._data = []
        else:
            self._data = []
            self._data.append(something)
    def push(self, obj):
        """Push an element on the Stack."""
        self._data.append(obj)
    def pop(self):
        """Pop an element from the Stack."""
        if len(self._data) > 0:
            result = self._data[-1]    # get the last (topmost) element
            del self._data[-1]
            return result
        else:
            raise StackError, "Stack is empty"
    def pushmore(self, seq):
        for item in seq: self.push(item)
    def popmore(self, number):
        seq = []
        for x in number: seq.append(self.pop())
        return seq
    def isempty(self):
        return len(self._data) == 0
    def num_items(self):
        return len(self._data)
    def __repr__(self):
        """Representation of a Stack."""
        return `self._data`
        # I'll take a list for this until I have something better
    def __len__(self):
        return len(self._data)
    # __add__ (+) is a replacement for push, nothing more, nothing less
    def __add__(self, obj):
        somestack = Stack(self)
        somestack.push(obj)
        return somestack
if __name__ == "__main__":
    stack1 = Stack()
    stack1.push(3)
    stack1.push('Hello')
    stack1.push([1,2,3])
    print 'stack1.num_items:', stack1.num_items()
    print 'topmost item:', stack1.pop()
    print 'stack1.num_items:', stack1.num_items()
    stack2 = Stack(stack1)
    print 'stack2.num_items:', stack2.num_items()
    # Doc string example
    print stack2.__doc__
    print stack2.push.__doc__
    print stack2.pop.__doc__
    print stack2._data
    class Queue(Stack): pass
    print 'Ahm trying to make a Queue from a Stack...'
    q1 = Queue()
    print q1._data
    q1.pushmore((3, 7, 21, 123))
    q1 = q1 + 4 + 6 + 8 + ('xyzzy', 'bletch', 'barf')
    q1 + 48 # doesn't work; ok
    print q1