标签:min ati init imp return waiting gets style 就是
模拟算法:打印任务 Queue来实现
问题:多人共享一台打印机,采取“先到先服务”的队列策略来执行打印任务
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)
作业问题:饭馆的餐桌设置,使得顾客排队时间变短?
标签:min ati init imp return waiting gets style 就是
原文地址:https://www.cnblogs.com/1314520xh/p/14788019.html