Stack implementation of Python Algorithms

Source: Internet
Author: User
This article mainly introduces the implementation of the Python algorithm stack, which is very practical. if you need it, you can refer to the following example to demonstrate the implementation of the stack in the Python algorithm, it has some reference value for learning data structure domain algorithms. The details are as follows:

1. stack operations:

Stack () creates an empty Stack object
Push () adds an element to the top layer of the stack
Pop () deletes the top-level element of the stack and returns this element.
Peek () returns the top-level element and does not delete it.
IsEmpty () determines whether the stack is empty
Size () returns the number of elements in the stack.

2. simple cases and operation results:

Stack Operation      Stack Contents   Return Value s.isEmpty()   []        True s.push(4)   [4]  s.push('dog')   [4,'dog']  s.peek()   [4,'dog']    'dog' s.push(True)   [4,'dog',True]  s.size()   [4,'dog',True]   3 s.isEmpty()   [4,'dog',True]   False s.push(8.4)   [4,'dog',True,8.4]  s.pop()       [4,'dog',True]   8.4 s.pop()       [4,'dog']     True s.size()   [4,'dog']     2

Here we use the python list object to simulate stack implementation. the specific code is as follows:

# Coding: utf8class Stack: "simulate Stack" def _ init _ (self): self. items = [] def isEmpty (self): return len (self. items) = 0 def push (self, item): self. items. append (item) def pop (self): return self. items. pop () def peek (self): if not self. isEmpty (): return self. items [len (self. items)-1] def size (self): return len (self. items) s = Stack () print (s. isEmpty () s. push (4) s. push ('dog ') print (s. peek () s. push (True) print (s. size () print (s. isEmpty () s. push (8.4) print (s. pop () print (s. pop () print (s. size ())

If you are interested, you can test the sample code described in this article. I believe it will be helpful for everyone to learn Python.

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.