Python stack implementation method, Python stack implementation method

Source: Internet
Author: User

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.

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.