Python Data Structure stack instance code, python Stack
Python Stack
A stack is a data structure of LIFO. The data structure of a stack can be used to process most program streams with the features of "first-in-first-out.
In the stack, push and pop are commonly used terms:
- Push: Refers to putting an object into the stack.
- Pop: It means to take an object out of the stack.
The following is a simple stack structure implemented by Python:
Stack = [] # initialize a list data type object as a stack def pushit (): # define an inbound stack method stack. append (raw_input ('enter New String :'). strip () # prompt to enter a String object in the stack and call Str. strip () ensures that the input String value does not contain any extra space def popit (): # define an out-of-stack method if len (stack) = 0: print "Cannot pop from an empty stack! "Else: print 'remove [', 'stack. pop () ','] '# Use reverse single quotes ('') instead of repr (), and extend the String value with quotation marks, not only does the String value def viewstack (): # defines a method for displaying the content in the stack. print stackCMDs = {'U': pushit, 'O': popit, 'V ': viewstack} # define a Dict type object that maps characters to the corresponding function. you can enter a character to execute the corresponding operation def showmenu (): # define an operation menu prompt method pr = "" p (U) sh p (O) p (V) iew (Q) uit Enter choice: "" while True: try: choice = raw_input (pr ). strip () [0]. lower () # Str. strip () removes extra spaces before and after the String object # Str. lower () converts multiple inputs into lower-case ones to facilitate unified judgment in the future # input ^ D (EOF, generates an EOFError exception) # input ^ C (interrupt and exit, generates a keyboardInterrupt exception) couldn t (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] () # obtain the functionName corresponding to the character in Dict, implement function call if _ name _ = '_ main _': showmenu ()
NOTE: In the stack data structure, the container and variable features of List data objects are mainly applied, as shown in List. append () and List. pop () is used to call the built-in functions of these two list types.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!