Python教程:双端队列

2018-10-1419:17:38数据结构与算法Comments3,251 views字数 952阅读模式

双端队列(或两端队列)具有从任一端添加和删除元素的功能。 Deque模块是集合库的一部分。 它具有添加和删除可以直接用参数调用的元素的方法。 在下面的程序中,将导入collections模块并声明一个双端队列。 不需要任何类,直接使用内置的实现这些方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6671.html

参数以下代码实现 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6671.html

import collections
# Create a deque
DoubleEnded = collections.deque(["Mon","Tue","Wed"])
print (DoubleEnded)

# Append to the right
print("Adding to the right: ")
DoubleEnded.append("Thu")
print (DoubleEnded)

# append to the left
print("Adding to the left: ")
DoubleEnded.appendleft("Sun")
print (DoubleEnded)

# Remove from the right
print("Removing from the right: ")
DoubleEnded.pop()
print (DoubleEnded)

# Remove from the left
print("Removing from the left: ")
DoubleEnded.popleft()
print (DoubleEnded)

# Reverse the dequeue
print("Reversing the deque: ")
DoubleEnded.reverse()
print (DoubleEnded)

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6671.html

deque(['Mon', 'Tue', 'Wed'])
Adding to the right: 
deque(['Mon', 'Tue', 'Wed', 'Thu'])
Adding to the left: 
deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu'])
Removing from the right: 
deque(['Sun', 'Mon', 'Tue', 'Wed'])
Removing from the left: 
deque(['Mon', 'Tue', 'Wed'])
Reversing the deque: 
deque(['Wed', 'Tue', 'Mon'])
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6671.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/suanfa/6671.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定