Python stack implementation method, Python stack implementation method
This article describes how to implement the stack in Python. Share it with you for your reference. The specific implementation method is as follows:
#! /Usr/bin/env python # define a list to simulate stack = [] # Into the stack. Call the list's append () function to add it to the end of the list, strip () if no parameter is specified, the space at the beginning and end is removed. def pushit (): stack. append (raw_input ('enter new string :'). strip () # The pop () function def popit (): if len (stack) = 0: print 'cannot pop from an empty stack! 'Else: print 'removed [', stack. pop (), ']' # edit the history stack def viewstack (): print stack # CMDs is used for 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: try: # Remove spaces with strip () and convert the first character to choice = raw_input (pr) in lower case ). strip () [0]. lower () handle T (EOFError, KeyboardInterrupt, IndexError): choice = 'q' print '\ nYou picked: [% s]' % choice if choice not in 'uovq ': print 'invalid option, try again 'else: break # CMDs [] returns the corresponding value from the dictionary based on the input choice. For example, if the input u is used, the value obtained from the dictionary is pushit, execute pushit () into the stack operation if choice = 'q': break CMDs [choice] () # determine whether the entry is from this file, instead of being called if _ name _ = '_ main _': showmenu ()
I hope this article will help you with Python programming.