Python循环缓冲器
循环缓冲器是环形缓冲器的另一个名字。缓冲区是一种数据结构,它使用一个单一的、固定大小的缓冲区,就像它是端对端连接一样。
这种结构有助于管理数据流,其中新的数据可以在一端不断添加,而旧的数据可以从另一端删除。当缓冲区满时,新数据将覆盖最旧的数据。
Python中高效的圆形缓冲区
高效的循环缓冲区是一种允许有效插入和删除数据的数据结构。
循环缓冲区通常被实现为一个数组。数组的头部指针指向第一个元素,而尾部指针表示数组中的最后一个元素。
当头部和尾部的指针到达数组的末端时,它们会被环绕。插入循环缓冲区是通过增加头部指针并将数据写入该位置的数组中来完成的。
从一个循环缓冲区中删除是通过增加尾部指针来完成的。这些数据并没有从数组中删除,但是头部和尾部指针有效地跳过了它。
循环缓冲区是一种高效的数据结构,因为它只需要固定数量的内存。它也很容易实现。
class Buffer:
def __init__(self, size):
self.data = [None for i in range(size)]
def append(self, x):
self.data.pop(0)
self.data.append(x)
def get(self):
return self.data
buf = Buffer(4)
for i in range(10):
buf.append(i)
print(buf.get())
输出:
[None, None, None, 0]
[None, None, 0, 1]
[None, 0, 1, 2]
[0, 1, 2, 3]
[1, 2, 3, 4]
[2, 3, 4, 5]
[3, 4, 5, 6]
[4, 5, 6, 7]
[5, 6, 7, 8]
[6, 7, 8, 9]
在Python中实现循环缓冲器
有很多方法可以在Python中实现高效的循环缓冲区。一种常见的方法是使用一个collections.dequeue
对象,该对象被设计为有效地支持从队列的前部和后部移除和添加元素。
另一种方法是使用一个列表,分别跟踪头部和尾部的索引。
如果你想知道哪种方法是最好的,这取决于应用程序的具体要求。例如,如果元素需要经常从缓冲区中添加和删除,而且顺序不是必须的,那么dequeue
方法可能是最好的。
另一方面,如果元素只被添加到缓冲区一次,然后被多次读出,或者顺序是必要的,那么列表的方法可能更好。
在Python中使用collections.enqueue
和collections.dequeue
实现循环队列
首先,我们将使用函数collections.enqueue
在队列中添加值。然后,我们可以在循环队列中使用collection.dequeue
,从队列中删除一个元素。
为了理解它的工作,让我们看一下Python中循环队列的实际例子。
示例代码:
# implememting circular queue in python
class CircularQueue():
def __init__(collections, k):
collections.k = k
collections.queue = [None] * k
collections.head = collections.tail = -1
# this function will insert (Enqueue) an element into the circular queue
def enqueue1(collections, data):
if ((collections.tail + 1) % collections.k == collections.head):
print("The queue is fulln")
elif (collections.head == -1):
collections.head = 0
collections.tail = 0
collections.queue[collections.tail] = data
else:
collections.tail = (collections.tail + 1) % collections.k
collections.queue[collections.tail] = data
# this function will delete (dequeue) an element from the circular
def dequeue1(collections):
if (collections.head == -1):
print("The circular queue is emptyn")
elif (collections.head == collections.tail):
temp = collections.queue[collections.head]
collections.head = -1
collections.tail = -1
return temp
else:
temp = collections.queue[collections.head]
collections.head = (collections.head + 1) % collections.k
return temp
# This function is used to print the queue
def printCQueue1(collections):
if(collections.head == -1):
print("Circular queue is empty")
elif (collections.tail >= collections.head):
for i in range(collections.head, collections.tail + 1):
print(collections.queue[i] , end=" ")
print()
else:
for i in range(collections.head, collections.k):
print(collections.queue[i] , end=" ")
for i in range(0, collections.tail + 1):
print(collections.queue[i] , end=" ")
print()
obj = CircularQueue(5)
# adding data to the queue
for i