Python:增加大小时,CircularQueue会加倍

时间:2018-09-15 23:04:35

标签: python python-3.x

我正在尝试修改类,所以当我超过当前容量时,容量会自动增加。尝试添加到完整队列时,容量增加了一倍。

我创建了一个新列表,其容量是原始容量的两倍。将原始列表中的项目排队到新列表中,以跟踪新的正面和背面。

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 is_full(self):
        return self.count == self.MAX_QUEUE
    def is_empty(self):
        return self.count == 0
    def size(self):
        return self.count

    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
            else:
                double_of_self_items = len(self.items)*2
                new_list = [None]* double_of_self_items
                MAX_QUEUE = double_of_self_items
                back = MAX_QUEUE - 1
                count = 0
                back = (back + 1) % MAX_QUEUE
                new_list[back] = self.items[back]
                count += 1
                print(new_list)
                return new_list


    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
            else:
                raise IndexError("The queue is empty.")

    def peek(self):
        if not self.is_empty():
            item = self.items[self.front]
            return item
        else:
            raise IndexError("The queue is empty.")

    def __str__(self):
        my_list = []
        for i in self.items[self.front:]:
            my_list.append(i)

        for i in self.items[:self.back + 1]:
            my_list.append(i)

        return str(my_list)




q = CircularQueue(2)
q.enqueue(10)
q.dequeue()
q.enqueue(20)
q.enqueue(30)
q.enqueue(40)
print(q.size())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())

Excepted result:
3
20
30
40

Actual Result:

[30, None, None, None]
[20, None, None, None]
[30, None, None, None]
[20, None, None, None]
[30, None, None, None]
[20, None, None, None]
2

1 个答案:

答案 0 :(得分:0)

我不确定您拥有什么代码,但是在您的enqueue方法中,只需检查您是否已满,然后增加大小,然后添加新项目。那应该简化您的逻辑,并通过减少流程来使代码更易于维护。

def enqueue(self,item):
        if is_full():
            self.items = self.items + [None] * self.SOME_KIND_OF_INCREASE_DEFAULT
            self.MAX_QUEUE = len(self.items)

        self.back = (self.back+1)%self.MAX_QUEUE
        self.items[self.back] = item
        self.count +=1