Can Python implement the structure of the stack?

Stack (stack), also known as stack, is a linear table with limited operations. It can be implemented in Python using lists.

What is a stack?

Stack (stack), also known as stack, is a linear table with limited operations. The limitation is that only insert and delete operations are allowed at one end of the table. This end is called the top of the stack, while the other end is called the bottom of the stack. Inserting a new element into a stack is also called pushing, pushing, or pushing on the stack. It puts the new element on top of the top element of the stack to make it a new top element; deleting an element from a stack is also called making a stack or Unstack, it deletes the top element of the stack so that the adjacent element becomes the new top element.

How to achieve?

Use lists in Python to achieve:

#! /usr/bin/env python 
# Define a list to simulate the stack
stack =[] 
# Push,Call the append of the list()Function added to the end of the list,strip()No parameter is to remove the leading and trailing spaces
def pushit(): 
 stack.append(raw_input('Enter new string: ').strip()) 
# Unstack,Used pop()function
def popit():iflen(stack)==0: 
 print 'Cannot pop from an empty stack!'else: 
 print 'Removed [', stack.pop(),']'
# Calendar stack
def viewstack(): 
 print stack 
# CMDs are the use of dictionaries
CMDs ={'u': pushit,'o': popit,'v': viewstack} 
# pr is the prompt character
def showmenu(): 
 pr =""" 
 p(U)sh 
 p(O)p(V)iew(Q)uit 
 Enter choice:"""
 while True:while True:try: 
 # First use strip()Remove spaces,Convert the first character to lowercase
 choice =raw_input(pr).strip()[0].lower()except(EOFError, KeyboardInterrupt, IndexError): 
 choice ='q'
 print '\nYou picked: [%s]'% choice 
 if choice not in'uovq': 
 print 'Invalid option, try again'else:break
# CMDs[]Corresponding to the corresponding value from the dictionary according to the input choice,For example, enter u,Get the value from the dictionary as pushit,Execute pushit()Push operation
 if choice =='q':break
 CMDs[choice]() 
# Determine whether it is entered from this file,Instead of being called
if __name__ =='__main__':showmenu()

Example content extension:

# - *- coding:utf-8-*-
# __ author__ :kusy
# __ content__:File description
# __ date__:2018/9/3017:28classMyStack(object):
 def __init__(self):
 self.stack_list =[]
 self.count =0

 # Create a stack
 def create_stack(self):return self.stack_list

 # Add value to the stack
 def push(self, value):
 self.stack_list.insert(0,value)
 self.count +=1

 # Returns the value of the top element on the stack
 def peek(self):if self.count:return self.stack_list[0]

 # Delete the top element
 def pop(self):
 self.stack_list.pop(0)
 self.count -=1

 # Return stack is empty
 def is_empty(self):return self.count ==0

 # Print stack contents
 def print_all(self):for sl in self.stack_list:print(sl)if __name__ =='__main__':
 ms =MyStack()
 ms.create_stack()
 ms.push(1)
 ms.push(2)
 ms.push(3)print('Stack element:')
 ms.print_all()print('Top element:',ms.peek())
 ms.pop()print('After the top element is deleted:')
 ms.print_all()print('Whether the stack is empty:','Yes'if ms.is_empty()else'no')print('---Continue to delete elements')
 ms.pop()print('---Continue to delete elements')
 ms.pop()print('Whether the stack is empty:','Yes'if ms.is_empty()else'no')

The results are as follows

C:\Users\suneee\AppData\Local\Programs\Python\Python36\python.exe E:/wangjz/PyWorkSpace/LearnPython/PY0929/stack.py
Stack element:321
Top element:3
After the top element is deleted:21
Whether the stack is empty:no
- - - Continue to delete elements
- - - Continue to delete elements
Whether the stack is empty:Yes

Process finished with exit code 0

So far, this article on whether Python can implement the structure of the stack is introduced. For more conditions related to the structure of the Python implementation of the stack, please search ZaLou.Cn

Recommended Posts

Can Python implement the structure of the stack?
Can the value of the python dictionary be modified?
Consolidate the foundation of Python (4)
Consolidate the foundation of Python(7)
Consolidate the foundation of Python(6)
Consolidate the foundation of Python(5)
Consolidate the foundation of Python (3)
The usage of wheel in python
Python handles the 4 wheels of Chinese
Python simulation of the landlord deal
What is the use of Python
The premise of Python string pooling
Secrets of the new features of Python 3.8
The father of Python joins Microsoft
The operation of python access hdfs
The usage of tuples in python
End the method of running python
Understanding the meaning of rb in python
Learn the basics of python interactive mode
What are the required parameters of python
Logistic regression at the bottom of python
The usage of Ajax in Python3 crawler
Python solves the Tower of Hanoi game
Solve the conflict of multiple versions of python
What is the scope of python variables
Python implements the sum of fractional sequences
Two days of learning the basics of Python
What is the id function of python
Where is the pip path of python3
The essence of Python language: Itertools library
What are the advantages of python language
The specific method of python instantiation object
python3 realizes the function of mask drawing
What is the prospect of python development
What is the function body of python
What kind of work can python do
The specific method of python import library
Solve the conflict of multiple versions of python
What is the function of adb in python
Detailed explanation of the principle of Python super() method
The difference between the syntax of java and python
7 features of Python3.9
Python realizes the development of student management system
Python implements the shuffling of the cards in Doudizhu
The meaning and usage of lists in python
Solve the problem of python running startup error
Python implements the source code of the snake game
Detailed explanation of the usage of Python decimal module
Python Lesson 32-Stack
How about learning python at the age of 27?
2.1 The Python Interpreter (python interpreter)
The consequences of uninstalling python in ubuntu, very
python data structure
Python writes the game implementation of fishing master
[898] python get the intersection of two lists | union | difference
Detailed explanation of the principle of Python function parameter classification
What is the advantage of python over corporate language
A brief summary of the difference between Python2 and Python3
Detailed explanation of the principle of Python timer thread pool
Solve the problem of python compiling and installing ssl
Detailed explanation of the implementation steps of Python interface development