Python算法之栈(stack)的实现

yipeiwu_com7年前Python基础

本文以实例形式展示了Python算法中栈(stack)的实现,对于学习数据结构域算法有一定的参考借鉴价值。具体内容如下:

1.栈stack通常的操作:

Stack() 建立一个空的栈对象
push() 把一个元素添加到栈的最顶层
pop() 删除栈最顶层的元素,并返回这个元素
peek()  返回最顶层的元素,并不删除它
isEmpty()  判断栈是否为空
size()  返回栈中元素的个数

2.简单案例以及操作结果:

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

这里使用python的list对象模拟栈的实现,具体代码如下:

#coding:utf8
class 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())

感兴趣的读者可以动手测试一下本文所述实例代码,相信会对大家学习Python能有一定的收获。

相关文章

Python中Class类用法实例分析

本文实例讲述了Python中Class类用法。分享给大家供大家参考,具体如下: 尽管Python在Function Programming中有着其他语言难以企及的的优势,但是我们也不要忘...

Python类装饰器实现方法详解

本文实例讲述了Python类装饰器。分享给大家供大家参考,具体如下: 编写类装饰器 类装饰器类似于函数装饰器的概念,但它应用于类,它们可以用于管理类自身,或者用来拦截实例创建调用以管理实...

基于MSELoss()与CrossEntropyLoss()的区别详解

基于MSELoss()与CrossEntropyLoss()的区别详解

基于pytorch来讲 MSELoss()多用于回归问题,也可以用于one_hotted编码形式, CrossEntropyLoss()名字为交叉熵损失函数,不用于one_hotted编...

Python编程之string相关操作实例详解

Python编程之string相关操作实例详解

本文实例讲述了Python编程之string相关操作。分享给大家供大家参考,具体如下: #coding=utf8 ''''' 字符串是Python中最常见的类型。可以通过引号见包含字...

初次部署django+gunicorn+nginx的方法步骤

环境 ubuntu16.04 python3.6 django1.11 gunicorn19.7.1 nginx1.10.3 写在前面 其实无论是在部署,还是在其他方面,我们总会遇到一...