Python data structure stack instance code
- 2020-05-24 05:45:18
- OfStack
Python stack
The stack is a last in, first out (LIFO) data structure that can be used to handle most flows of programs with a last in, first out nature.
In the stack, push and pop are common terms:
Here is a simple stack structure implemented by Python:
stack = [] # Initialize the 1 List data type objects , As a 1 A stack
def pushit(): # define 1 A push method
stack.append(raw_input('Enter New String: ').strip())
# prompt 1 A stack String object , call Str.strip() Guaranteed input String The value does not contain extra Spaces
def popit(): # define 1 A stack method
if len(stack) == 0:
print "Cannot pop from an empty stack!"
else:
print 'Remove [', `stack.pop()`, ']'
# Use inverted single quotes (` `) To take the place of repr(), the String Is enclosed in quotation marks , Instead of just showing String The value of the
def viewstack(): # define 1 Method to display the contents of the stack
print stack
CMDs = {'u':pushit, 'o':popit, 'v':viewstack}
# define 1 a Dict Type of object , Map the character to the corresponding function . You can do this by entering characters
def showmenu(): # define 1 Action menu prompt method
pr = """
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
# Str.strip() Get rid of String Extra space before and after the object
# Str.lower() Converts multiple inputs to lowercase , It is convenient for the later unification 1 judge
# The input ^D(EOF, produce 1 a EOFError abnormal )
# The input ^C( Break out , produce 1 a keyboardInterrupt abnormal )
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'uovq':
print 'Invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
# To obtain Dict Corresponding to the Chinese character functionName, Implement function calls
if __name__ == '__main__':
showmenu()
NOTE: in the stack data structure, List data type object container and variable features are mainly applied. List.append () and List.pop () are two list types with built-in function calls.
Thank you for reading, I hope to help you, thank you for your support of this site!