python的模拟算法--打印任务
模拟算法:打印任务 Queue来实现
队列(queue)是一种有次序的数据集合,其特征是新数据项的添加总发生在一端(通常称为“尾rear”端)而现存数据项的移除总发生在另一端(通常称为“首front”端)
问题:多人共享一台打印机,采取“先到先服务”的队列策略来执行打印任务
在这种设定下,一个首要的问题就是:
1、这种打印作业系统的容量有多大?
2、在能够接受的等待时间内,系统能容纳多少用户
3、以多高频率提交多少打印任务?
如何对问题建模?
1、首先对问题进行抽象,确定相关的对象和过程抛弃那些对问题实质没有关系的学生性别、
年龄、打印机型号、打印内容、纸张大小等等众多细节
class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): # 队列首段加选项 self.items.insert(0, item) def dequeue(self): # 队列尾端出 return self.items.pop() def size(self): return len(self.items)
import random class Printer: def __init__(self, ppm): self.pagerate = ppm self.currentTask = None self.timeRemaining = 0 def tick(self): if self.currentTask is not None: self.timeRemaining = self.timeRemaining - 1 if self.timeRemaining <= 0: self.currentTask = None def busy(self): if self.currentTask != None: return True else: return False def startNext(self, newtask): self.currentTask = newtask self.timeRemaining = newtask.getPages() * 60 / self.pagerate class Task: def __init__(self, time): self.timestamp = time self.pages = random.randrange(1, 21) def getStamp(self): return self.timestamp def getPages(self): return self.pages def waitTime(self, currenttime): return currenttime - self.timestamp def newPrintTask(): num = random.randrange(1, 181) if num == 180: return True else: return False def simulation(numSeconds, pagesPerMinute): labprinter = Printer(pagesPerMinute) printQueue = Queue() waitingtimes = [] for currentSecond in range(numSeconds): if newPrintTask(): task = Task(currentSecond) printQueue.enqueue(task) if (not labprinter.busy()) and (not printQueue.isEmpty()): nexttask = printQueue.dequeue() waitingtimes.append(nexttask.waitTime(currentSecond)) labprinter.startNext(nexttask) labprinter.tick() averageWait = sum(waitingtimes) / len(waitingtimes) print("average wait %6.2f secs %3d task remaining" % (averageWait, printQueue.size()))
调用
for i in range(10): simulation(3600,5)
作业问题:饭馆的餐桌设置,使得顾客排队时间变短?
心有猛虎,细嗅蔷薇