Stack implementation using Python

Source: Internet
Author: User

This is an example of Python core programming:
[Python]
#! /Usr/bin/env python
 
# Define a list to simulate stacks
Stack = []
 
# Stack: The append () function of the call list is added to the end of the list. If strip () does not have a parameter, spaces at the beginning and end are removed.
Def pushit ():
Stack. append (raw_input ('enter new string: '). strip ())
 
# The pop () function is used for the output stack.
Def popit ():
If len (stack) = 0:
Print 'cannot pop from an empty stack! '
Else:
Print 'removed [', stack. pop (),']'
 
# Editing Stack
Def viewstack ():
Print stack
 
# CMDs is used as a dictionary
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:
While True:
Try:
# Remove spaces with strip () and convert the first character to lowercase letters.
Choice = raw_input (pr). 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 [] corresponds to the corresponding value from the dictionary based on the input choice. For example, if the input u is used, the value is pushit from the dictionary and pushit () is executed for Stack import.
If choice = 'q ':
Break
CMDs [choice] ()
 
# Determine whether the file is in, rather than being called
If _ name _ = '_ main __':
Showmenu ()

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.