循环队列 Class 实现 __str__ 方法

Circular Queue Class implementation __str__ method

对于我的练习题,我的任务是在Python中实现以下CircularQueueclass。我已经完成了实现,但仍停留在 __str__ 方法上,因为我不知道如何使其与预期输出相匹配。

class CircularQueue:

    def __init__(self, capacity):
        self.items = [None] * capacity
        self.max_queue = capacity
        self.front = 0
        self.back = self.max_queue - 1
        self.count = 0

    def enqueue(self, item):
        if not self.is_full():
            self.back = (self.back + 1) % self.max_queue
            self.items[self.back] = item
            self.count += 1

    def dequeue(self):
        if not self.is_empty():
            item = self.items[self.front]
            self.front = (self.front + 1) % self.max_queue
            self.count -= 1
            return item

    def is_full(self):
        return self.count == self.max_queue

    def is_empty(self):
        return self.count == 0

    def peek(self):
        return self.items[self.front]
        
    def __str__(self): #my issue is here
        return "Front {} Rear".format(self.items)

测试:

q = CircularQueue(7)
q.enqueue("abc")
q.enqueue("def")
q.dequeue()
q.enqueue(8)
q.enqueue(9)
q.enqueue(10)
q.enqueue(11)
q.dequeue()
q.enqueue("hello")
q.enqueue("world")
print(q)

预期输出:

Queue: Front [8, 9, 10, 11, hello, world] Rear

得到:

Queue: Front [8, 9, 10, 11, 'hello', 'world'] Rear

测试:

q = CircularQueue(4)
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.dequeue()
q.dequeue()
print(q)
q.dequeue()
q.dequeue()
print(q)

预期输出:

Queue: Front [3, 4] Rear
Queue: Front [] Rear

获取输出:

Front [1, 2, 3, 4] Rear
Front [1, 2, 3, 4] Rear

一种方法是将循环队列中的项目添加到列表中。

def __str__(self):
    items = []
    if self.count > 0:
        i = self.front
        if i > self.back:
            # we need to loop around
            items.extend(self.items[i:])
            i = 0
        items.extend(self.items[i:self.back + 1])
    return "Queue: Front [{}] Rear".format(", ".join(str(x) for x in items))

另一种可能的方法是在 class.

上定义一个迭代器
def __iter__(self):
    if self.count == 0:
        return
    i = self.front
    end = self.back
    if i > end:
        while i < self.max_queue:
            yield self.items[i]
            i += 1
        i = 0
    while i <= self.back:
        yield self.items[i]
        i += 1

def __str__(self):
    return "Queue: Front [{}] Rear".format(", ".join(str(x) for x in self))