開始使用免費開始

為印表機工作實作佇列

在上一支影片中,你學到佇列有多種應用,例如用來管理印表機的工作。

在這個練習中,你將實作一個名為 PrinterTasks() 的類別,代表一個簡化版的印表機佇列。為了達成這件事,會提供給你一個包含以下方法的 Queue() 類別:

  • enqueue(data):將元素加入佇列
  • dequeue():從佇列移除一個元素
  • has_elements():檢查佇列中是否有元素。其程式碼如下:
    def has_elements(self):
      return self.head != None

你會從 PrinterTasks() 類別開始撰寫,實作其中的 add_document()print_documents() 方法。之後,你會模擬一個使用 PrinterTasks() 類別的程式執行流程。

本練習屬於課程

Data Structures and Algorithms in Python

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

class PrinterTasks:
  def __init__(self):
    self.queue = Queue()
      
  def add_document(self, document):
    # Add the document to the queue
    self.____.____(document)
      
  def print_documents(self):
    # Iterate over the queue while it has elements
    while self.____.____():
      # Remove the document from the queue
      print("Printing", self.____.____())
編輯並執行程式碼