Python implements stack and queue methods

  • 2020-04-02 14:28:26
  • OfStack

This article illustrates how python implements stacks and queues. Share with you for your reference. Specific analysis is as follows:

1. In python, Stack can be implemented by first writing the Stack class to the file stack.py and then using from Stack import Stack in other program files. Then the Stack can be used.

Stack.py:

class Stack():  
    def __init__(self,size): 
        self.size=size; 
        self.stack=[]; 
        self.top=-1; 
    def push(self,ele):  # Check that the stack is full before pushing  
        if self.isfull(): 
            raise exception("out of range"); 
        else: 
            self.stack.append(ele); 
            self.top=self.top+1; 
    def pop(self):             # Check that the stack is empty before pushing  
        if self.isempty(): 
            raise exception("stack is empty"); 
        else: 
            self.top=self.top-1; 
            return self.stack.pop(); 
     
    def isfull(self): 
        return self.top+1==self.size; 
    def isempty(self): 
        return self.top==-1;

 
Write another program file, stacktest.py, using the stack, as follows:
 
#!/usr/bin/python   
from stack import Stack 
s=Stack(20); 
for i in range(3): 
    s.push(i); 
s.pop() 
print s.isempty();

2. Python implementation queue:

class Queue():  
    def __init__(self,size): 
        self.size=size; 
        self.front=-1; 
        self.rear=-1; 
        self.queue=[]; 
    def enqueue(self,ele):  # The operation of entrance  
        if self.isfull(): 
            raise exception("queue is full"); 
        else: 
            self.queue.append(ele); 
            self.rear=self.rear+1; 
    def dequeue(self):      # The team operation  
        if self.isempty(): 
            raise exception("queue is empty"); 
        else: 
            self.front=self.front+1; 
            return self.queue[self.front]; 
    def isfull(self): 
        return self.rear-self.front+1==self.size; 
    def isempty(self): 
        return self.front==self.rear; 
     
q=Queue(10); 
for i in range(3): 
    q.enqueue(i); 
print q.dequeue(); 
print q.isempty();

I hope this article has helped you with your Python programming.


Related articles: