Implementation of the Python algorithm stack

  • 2020-04-02 13:54:23
  • OfStack

This paper presents the implementation of stack in Python algorithm in the form of an example, which has certain reference value for learning data structure domain algorithm. The specific contents are as follows:

1. Common operation of stack:

Stack() creates an empty Stack object
Push () adds an element to the top of the stack
Pop () deletes the topmost element of the stack and returns it
Peek ()   Returns the topmost element without deleting it
IsEmpty ()   Determines if the stack is empty
The size ()   Returns the number of elements in the stack

2. Simple cases and operational results:


Stack Operation      Stack Contents   Return Value
 s.isEmpty()   []        True
 s.push(4)   [4] 
 s.push('dog')   [4,'dog'] 
 s.peek()   [4,'dog']    'dog'
 s.push(True)   [4,'dog',True] 
 s.size()   [4,'dog',True]   3
 s.isEmpty()   [4,'dog',True]   False
 s.push(8.4)   [4,'dog',True,8.4] 
 s.pop()       [4,'dog',True]   8.4
 s.pop()       [4,'dog']     True
 s.size()   [4,'dog']     2

Here, the list object of python is used to simulate the implementation of the stack. The specific code is as follows:


#coding:utf8
class Stack:
  """ Simulation of the stack """
  def __init__(self):
    self.items = []
    
  def isEmpty(self):
    return len(self.items)==0 
  
  def push(self, item):
    self.items.append(item)
  
  def pop(self):
    return self.items.pop() 
  
  def peek(self):
    if not self.isEmpty():
      return self.items[len(self.items)-1]
    
  def size(self):
    return len(self.items) 
s=Stack()
print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())

Interested readers can take a hands-on test of the example code described in this article, I believe that you can learn Python to some extent.


Related articles: