Python stack implementation method

Source: Internet
Author: User

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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

#! /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 ()

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.