开始使用免费开始使用

为打印任务实现一个队列

在上一段视频中,您了解到队列有多种应用场景,例如管理打印机的任务。

在本练习中,您将实现一个名为 PrinterTasks() 的类,用来表示一个简化的打印机队列。为此,您将获得包含以下方法的 Queue() 类:

  • enqueue(data):向队列添加一个元素
  • dequeue():从队列移除一个元素
  • has_elements():检查队列是否包含元素。代码如下:
    def has_elements(self):
      return self.head != None

您将开始编写 PrinterTasks() 类及其 add_document()print_documents() 方法。随后,您将模拟一个使用 PrinterTasks() 类的程序执行过程。

本练习是课程的一部分

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.____.____())
编辑并运行代码