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