簡體   English   中英

谷歌 colab 上的 Python Class

[英]Python Class on google colab

為什么我的代碼只能打印到 3,然后我得到 0?

誰能幫我解決這個問題?

我不知道錯誤在哪里。

謝謝!

這是我的代碼:

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]

這是我的結果:

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 是最新元素 + 1 的索引,調用 get 方法時實際上並沒有從隊列中刪除任何元素。 不需要在 get 方法中減少 self.__head 。 執行下一個添加元素將替換舊元素。 刪除“self.__head -= 1”,一切都會正常進行(只要您不會向隊列中添加超過 10 個元素)。

但是,基於數組的隊列是個壞主意。 要實現隊列,您應該使用鏈表之類的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM