python双端队列原理、实现与使用方法分析

yipeiwu_com7年前Python基础

本文实例讲述了python双端队列原理、实现与使用方法。分享给大家供大家参考,具体如下:

双端队列

双端队列(deque,全名double-ended queue),是一种具有队列和栈的性质的数据结构。

双端队列中的元素可以从两端弹出,其限定插入和删除操作在表的两端进行。双端队列可以在队列任意一端入队和出队。

操作

Deque() 创建一个空的双端队列
add_front(item) 从队头加入一个item元素
add_rear(item) 从队尾加入一个item元素
remove_front() 从队头删除一个item元素
remove_rear() 从队尾删除一个item元素
is_empty() 判断双端队列是否为空
size() 返回队列的大小

实现

class Deque(object):
  """双端队列"""
  def __init__(self):
    self.items = []
  def is_empty(self):
    """判断队列是否为空"""
    return self.items == []
  def add_front(self, item):
    """在队头添加元素"""
    self.items.insert(0,item)
  def add_rear(self, item):
    """在队尾添加元素"""
    self.items.append(item)
  def remove_front(self):
    """从队头删除元素"""
    return self.items.pop(0)
  def remove_rear(self):
    """从队尾删除元素"""
    return self.items.pop()
  def size(self):
    """返回队列大小"""
    return len(self.items)
if __name__ == "__main__":
  deque = Deque()
  deque.add_front(1)
  deque.add_front(2)
  deque.add_rear(3)
  deque.add_rear(4)
  print deque.size()
  print deque.remove_front()
  print deque.remove_front()
  print deque.remove_rear()
  print deque.remove_rear()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python回调函数中使用多线程的方法

下面的demo是根据需求写的简单测试脚本 #!/usr/bin/env python # coding: utf-8 # 第一个列表为依赖组件和版本号,后面紧跟负责人名称 # 接着出...

python3使用matplotlib绘制散点图

python3使用matplotlib绘制散点图

本文实例为大家分享了python3使用matplotlib绘制散点图,并标注图例,轴,供大家参考,具体内容如下 代码 from matplotlib import pyplot as...

python读取几个G的csv文件方法

如下所示: import pandas as pd file = pd.read_csv('file.csv',iterator=True) while True: chunk...

Python中的引用和拷贝浅析

If an object's value can be modified, the object is said to be mutable. If the value cannot b...

python中常用的九种预处理方法分享

python中常用的九种预处理方法分享

本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(Standardization or Mean R...