Skip to content

Instantly share code, notes, and snippets.

@cyyeh
Created March 18, 2017 00:29
Show Gist options
  • Save cyyeh/35cb02d52d11ac4209890f382c18ae72 to your computer and use it in GitHub Desktop.
Save cyyeh/35cb02d52d11ac4209890f382c18ae72 to your computer and use it in GitHub Desktop.
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)
# application1 using Queue: Hot Potato Simulation
def hotPotato(namelist, num):
simqueue = Queue()
for name in namelist:
simqueue.enqueue(name)
while simqueue.size() > 1:
for i in range(num):
simqueue.enqueue(simqueue.dequeue())
simqueue.dequeue()
return simqueue.dequeue()
# application2 using Queue: Print Tasks Simulation
class Printer:
def __init__(self, ppm):
self.pagerate = ppm
self.currentTask = None
self.timeRemaining = 0
def tick(self):
if self.currentTask != None:
self.timeRemaining = self.timeRemaining - 1
if self.timeRemaining <= 0:
self.currentTask = None
def busy(self):
return self.currentTask != None
def startNext(self, newtask):
self.currentTask = newtask
self.timeRemaining = newtask.getPages() * 60 / self.pagerate
import random
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 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 tasks remaining."%(averageWait, printQueue.size()))
def newPrintTask():
return random.randrange(1, 181) == 180
def main():
q = Queue()
print(q.size())
q.enqueue(8.4)
print(q.size())
print(q.dequeue())
print(q.isEmpty())
print(hotPotato(["Bill","David","Susan","Jane","Kent","Brad"], 7))
for i in range(10):
simulation(3600, 5)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment