简体   繁体   English

谷歌 colab 上的 Python Class

[英]Python Class on google colab

Why my code can only print until 3, then I get 0 after all?为什么我的代码只能打印到 3,然后我得到 0?

Can anyone help me with this question?谁能帮我解决这个问题?

I don't know where is the Error.我不知道错误在哪里。

Thank you!谢谢!

Here are my code:这是我的代码:

class Queue:
  def __init__ (self,size):
    self.__contents = [0] * 10
    self.__head = 0
    self.__count = -1
  
  def is_full(self):
    return self.__head > len(self.__contents)

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

  def add(self, x):
    if self.is_full():
      return
    else:
      self.__contents[self.__head] = x
      self.__head += 1
  
  def get(self):
    if self.is_empty():
      return
    else:
      self.__head -= 1
      self.__count += 1
      return self.__contents[self.__count]

Here are my result:这是我的结果:

my_queue = Queue(5)
my_queue.add(4)
my_queue.add(10)
my_queue.add(3)
print(my_queue.get()) # should print 4 I get 4. Success!
print(my_queue.get()) # should print 10 I get 10. Success!
my_queue.add(7)
print(my_queue.get()) # should print 3 I get 3. Success!
my_queue.add(6)
my_queue.add(5)
my_queue.add(4)
my_queue.add(3)     # should print 7 but I get 0. Fail
print(my_queue.get()) # should print 6 but I get 0. Fail
print(my_queue.get()) # should print 5 but I get 0. Fail
print(my_queue.get()) # should print 4 but I get 0. Fail
print(my_queue.get()) # should print 3 but I get 0. Fail

self.__head is the index of the newest element + 1 and you don't actually remove any element from the queue when calling the get method. self.__head 是最新元素 + 1 的索引,调用 get 方法时实际上并没有从队列中删除任何元素。 There is no need to decrease self.__head inside the get method.不需要在 get 方法中减少 self.__head 。 Doing that next added element will replace the old ones.执行下一个添加元素将替换旧元素。 Remove "self.__head -= 1" and everything will work (as long as you won't add more than 10 elements to the queue).删除“self.__head -= 1”,一切都会正常进行(只要您不会向队列中添加超过 10 个元素)。

However, array based queue is a bad idea.但是,基于数组的队列是个坏主意。 To implement a queue you should use something like linked lists.要实现队列,您应该使用链表之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM