class Queue:
def __init__(self):
self.data = []
def enqueue(self,value):
self.data.append(value)
def dequeue(self):
if len(self.data)>0:
return self.data.pop(0)
else:
return None
def read(self):
if len(self.data)>0:
return self.data[0]
else:
return None
def __repr__(self):
return f"{self.data!r}"
# def __str__(self):
# print(f"{self.data!r}")
1. Build a PrintManager
class
1.1 The Task
- Build a simple Python interface for a printer that can accept printing jobs.
- Ensure print each document in the order in which it was received.
2. Psuedo-Code Solution
2.1 Add Queue
class:
enqueue(value)
: addvalue
toqueue
dequeue()
: removefirst
item fromqueue
read()
: peek atfirst
fromqueue
2.2 Add Printer
class:
add_job_to_queue(job)
: addjob
toqueue
print(job)
: printjob
run()
:dequeue()
each job thenprint(job)
from front to back
3. Python-Code Solution
3.1 Queue
class
From queue class implementation post.
3.2 Queue
: Testing
= Queue()
tp_q 1)
tp_q.enqueue(print(tp_q)
2)
tp_q.enqueue(print(tp_q)
3)
tp_q.enqueue(print(tp_q)
tp_q.dequeue()print(tp_q)
4)
tp_q.enqueue(print(tp_q)
5)
tp_q.enqueue(print(tp_q)
6)
tp_q.enqueue(print(tp_q)
tp_q.dequeue()print(tp_q)
tp_q.dequeue()print(tp_q)
tp_q.dequeue()print(tp_q)
tp_q.dequeue()print(tp_q)
tp_q.dequeue()print(tp_q)
tp_q.dequeue()
[1]
[1, 2]
[1, 2, 3]
[2, 3]
[2, 3, 4]
[2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]
3.3 PrintManager
class
class PrintManager():
def __init__(self):
self.queue = Queue()
def add_job(self, job):
self.queue.enqueue(job)
print(f"{job!r} added: {self.queue}")
def run(self):
while self.queue.read():
= self.queue.dequeue()
current_job self.print_job(current_job)
def print_job(self,job):
print(job)
3.4 PrintManager
class: Testing
= PrintManager()
printer "doc1.md")
printer.add_job("doc2.docx")
printer.add_job("doc3.pdf")
printer.add_job( printer.run()
'doc1.md' added: ['doc1.md']
'doc2.docx' added: ['doc1.md', 'doc2.docx']
'doc3.pdf' added: ['doc1.md', 'doc2.docx', 'doc3.pdf']
doc1.md
doc2.docx
doc3.pdf