Python Stack
A stack is a last-in, first-out (LIFO) data structure. This data structure of the stack can be used to process most of the program flows with last-in-first-out features.
In the stack, push and pop are common terms:
Push: Means to put an object into the stack.
Pop: means to put an object out of the stack.
The following is a simple stack structure implemented by Python:
stack = [] # Initializes a list data type object, as a stack def pushit (): # defines a stack method Stack.append (raw_input (' Enter New String: '). str IP ()) # Prompt for a string object into the stack, call Str.strip () to ensure that the input string value does not contain extra spaces def popit (): # defines a stack method if Len (stack) = = 0: Print "Cannot pop from an empty stack!" Else:print ' Remove [', ' Stack.pop () ', '] ' # uses anti-single quotation marks (') instead of repr () to extend the string value in quotation marks, not only the value of string def viewstack (): # Defines a way to display the contents of a stack print stack CMDs = {' U ':p ushit, ' o ':p opit, ' V ': viewstack}# defines a Dict type object that maps characters to the corresponding functio N. You can use the input characters to perform the corresponding Operation Def ShowMenu (): # Defines an Action menu prompt method PR = "" "P (U) SH p (O) p (V) iew (Q) uit Enter choice:" "whi Le true:while True:try:choice = raw_input (pr). Strip () [0].lower () # Str.strip () remove extra space before and after a String object Lattice # str.lower () converts multiple inputs into lowercase to facilitate later unified judgment # Input ^d (EOF, which produces a eoferror exception) # input ^c (interrupt exit, resulting in a keyboardinter Rupt exception) 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] () # gets Dict characters corresponding to functionname, implement function call if __name__ = = ' __main__ ': s Howmenu ()
Note: In the stack data structure, the main application is the container of the list data type object and the mutable attributes, which are represented in the call of the List.append () and List.pop () in the built function of the list type.
Thank you for reading, hope to help everyone, thank you for the support of this site!