How Python implements the stack

Source: Internet
Author: User
The example in this paper describes how Python implements the stack. Share to everyone for your reference. The implementation method is as follows:

#!/usr/bin/env python #定义一个列表来模拟栈 stack = [] #进栈, the Append () function of the invocation list is added to the end of the list, strip () No parameters are stripped-down spaces def pushit (): Stack.append ( Raw_input (' Enter new string: '). Strip ()) #出栈, using the Pop () function Def popit (): If Len (stack) = = 0:print ' cannot pop from an E   Mpty stack! ' Else:print ' Removed [', Stack.pop (), '] ' #编历栈 def viewstack (): print stack #CMDs是字典的使用 CMDs = {' U ': pushit, ' o ': PO Pit, ' V ': viewstack} #pr为提示字符 def showmenu (): PR = "" "P (U) SH p (O) p (v) iew (Q) uit Enter choice:" "while       True:while true:try: #先用strip () Remove the space and 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 [] corresponds to the corresponding v from the dictionary according to the choice of the input Alue, for example, enter U, get value as Pushit from the dictionary, execute Pushit () into the stack operation if choice = = ' Q ': Break Cmds[choice] () #判断是否是从本文件进入 instead of being called if __name__ == ' __main__ ': ShowMenu ()  

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.