Implementing Stack with Python

前端 未结 12 1080
长发绾君心
长发绾君心 2021-01-17 16:16

I am trying to implement a simple stack with Python using arrays. I was wondering if someone could let me know what\'s wrong with my code.

class myStack:
            


        
12条回答
  •  醉梦人生
    2021-01-17 16:53

    A stack is a container (linear collection) in which dynamic set operations are carried out as per the last-in first-out (LIFO) principle. There is only one pointer - top, which is used to perform these operations

    CLRS implementation of stack using array:

    class Stack:
        """
        Last in first out (LIFO) stack implemented using array.
        """
        def __init__(self, capacity=4):
            """
            Initialize an empty stack array with default capacity of 4.
            """
            self.data = [None] * capacity
            self.capacity = capacity
            self.top  = -1
    
        def is_empty(self):
            """
            Return true if the size of stack is zero.
            """
            if self.top == -1:
                return True
            return False
    
        def push(self, element):
            """
            Add element to the top.
            """
            self.top += 1
            if self.top >= self.capacity:
                raise IndexError('Stack overflow!')
            else:
                self.data[self.top] = element
    
        def pop(self):
            """
            Return and remove element from the top.
            """
            if self.is_empty():
                raise Exception('Stack underflow!')
            else:
                stack_top = self.data[self.top]
                self.top -= 1
                return stack_top
    
        def peek(self):
            """
            Return element at the top.
            """
            if self.is_empty():
                raise Exception('Stack is empty.')
                return None
            return self.data[self.top]
    
        def size(self):
            """
            Return the number of items present.
            """
            return self.top + 1
    
    

    Testing the implemetation:

    def main():
        """
        Sanity test
        """
        stack = Stack()
    
        print('Size of the stack is:', stack.size())
        stack.push(3)
        print('Element at the top of the stack is: ', stack.peek())
        stack.push(901)
        print('Element at the top of the stack is: ', stack.peek())
        stack.push(43)
        print('Element at the top of the stack is: ', stack.peek())
        print('Size of the stack is:', stack.size())
        stack.push(89)
        print('Element at the top of the stack is: ', stack.peek())
        print('Size of the stack is:', stack.size())
        #stack.push(9)    # Raises IndexError
        stack.pop()
        print('Size of the stack is:', stack.size())
        stack.pop()
        print('Size of the stack is:', stack.size())
        stack.pop()
        print('Size of the stack is:', stack.size())
        print('Element at the top of the stack is: ', stack.peek())
        stack.pop()
        #print('Element at the top of the stack is: ', stack.peek())    # Raises empty stack exception
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题