2016-12-02 99 views
0

我试图完成循环阵列支持队列的最后一种方法。我被困在调整大小的方法。任何帮助或指针表示赞赏。环形阵列支持的队列调整大小/排队

def resize(self, newsize): 
    assert(len(self.data) < newsize) 
    new = Queue(newsize) 
    for x in range(len(self.data)): 
     new[x] == self.data[x] 
    self.data = new 

错误我得到的是:

<ipython-input-31-d458e1ceda34> in <module>() 
    19 
    20 for i in range(9, 14): 
---> 21  q.enqueue(i) 
    22 
    23 for i in range(4, 14): 

    <ipython-input-28-0e6c7038d634> in enqueue(self, val) 
     9 
    10  def enqueue(self, val): 
---> 11   if self.head == (self.tail + 1) % len(self.data): 
    12    raise RuntimeError 
    13   elif self.head == -1 and self.tail == -1: 

TypeError: object of type 'Queue' has no len() 

我的排队方法是这样的,给我任何错误别处:

def enqueue(self, val): 
    if self.head == (self.tail + 1) % len(self.data): 
     raise RuntimeError 
    elif self.head == -1 and self.tail == -1: 
     self.head = 0 
     self.tail = 0 
     self.data[self.tail] = val 
    else: 
     self.tail = (self.tail + 1) % len(self.data) 
     self.data[self.tail] = val 

回答

0

Queue类需要__len__方法:

>>> class Queue: 
...  pass 
... 
>>> len(Queue()) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: object of type 'Queue' has no len() 
>>> class Queue: 
...  def __len__(self): 
...   return 0 
... 
>>> len(Queue()) 
0 

当调用内置方法len时,它将在内部调用传递对象的__len__。如果对象没有定义__len__,则会显示上述示例中的错误。