The implementation of Python algorithm stacks (stack) _python

Source: Internet
Author: User

In this paper, the implementation of stack in Python algorithm is illustrated by example, which has some reference value for learning data structure domain algorithm. The specific contents are as follows:

1. Stack stack The usual operation:

Stack () to create an empty stack object
Push () Adds an element to the topmost level of the stack
Pop () deletes the topmost element of the stack and returns the element
Peek () returns the topmost element and does not delete it
IsEmpty () to determine whether the stack is empty
Size () returns the number of elements in the stack

2. Simple case and operation result:

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

This uses Python's list object to simulate the implementation of the stack, as follows:

#coding: UTF8
class Stack: ""
  Analog Stack ""
  def __init__ (self):
    self.items = []
    
  def isempty (self):
    Return Len (self.items) ==0 
  
  def push (self, item):
    self.items.append (item)
  
  def pops (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 ())


Interested readers can test the example code described in this article, I believe that you will learn python can have a certain harvest.

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.