def check(): # Code for checking the results ans_check = input('Do you want to print the result in dorder they were played or sorted? \n \ [Enter "o" for in order and "s" for sorted]\n') if ans_check == 'o': f = open('result.txt','r') # Another way to operate file I/O result = Queue() for line in open('result.txt'): line = line.strip() # To make the output more clear result.enqueue(line) while result.size()>1: print(result.dequeue()) f.close() if ans_check == 's': f = open('result.txt','r') result = [] # Read lines and store it as a list for line in open('result.txt'): line = line.strip() result.append(line) result.sort() # Sorted for item in result: print(item) f.close()
def send_flowers(name_list, num): simqueue = Queue() for name in name_list: simqueue.enqueue(name) while simqueue.size() > 1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) print(simqueue.dequeue()) return simqueue.dequeue()
def send_flower(name_list, num): q = Queue() for name in name_list: q.enqueue(name) while q.size() > 1: for i in range(num): q.enqueue(q.dequeue()) print(q.dequeue()) return q.dequeue()
def safe_postion(num_soldiers): queue_sol = Queue() # Declare an Empty Queue # Adding the list-num_soldiers to Queue using push for name in num_soldiers: queue_sol.enqueue(name) # looping through the soldires and killing the next to it # list_a =[] print("Original Circle:%s " % (queue_sol.items)) while queue_sol.size() > 1: for i in range(1): k = queue_sol.enqueue(queue_sol.dequeue()) print('-' * 30) #s = s.join(queue_sol.items) print("Remaining Soldier:", "".join(queue_sol.items)) #print("Remaining Soldier:%s" % (queue_sol.items)) print('-' * 30) #print('%s Kills: '%(queue_sol.items[0])) n = queue_sol.dequeue() print(queue_sol.items[0] + ' Kills: ' + n) time.sleep(1) return queue_sol.dequeue()
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
def hotPotato(namelist, num): q = Queue() for name in namelist: q.enqueue(name) while q.size() > 1: for i in range(num): q.enqueue(q.dequeue()) q.dequeue() return q.dequeue()
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()
def hotPotato(namelist, num): simqueue = Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size() > 1: for i in range(1, num): simqueue.enqueue(simqueue.dequeue()) temp = simqueue.dequeue() print(temp + "*" * 10) return simqueue.dequeue()
def __init__(self): # 创建一个队列用来保存进程获取到的数据 self.q = Queue() self.headers = { 'Cookie': 'll="118282"; bid=ctyiEarSLfw; ps=y; __yadk_uid=0Sr85yZ9d4bEeLKhv4w3695OFOPoedzC; dbcl2="155150959:OEu4dds1G1o"; as="https://sec.douban.com/b?r=https%3A%2F%2Fbook.douban.com%2F"; ck=fTrQ; _pk_id.100001.4cf6=c86baf05e448fb8d.1506160776.3.1507290432.1507283501.; _pk_ses.100001.4cf6=*; __utma=30149280.1633528206.1506160772.1507283346.1507290433.3; __utmb=30149280.0.10.1507290433; __utmc=30149280; __utmz=30149280.1506160772.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=223695111.1475767059.1506160772.1507283346.1507290433.3; __utmb=223695111.0.10.1507290433; __utmc=223695111; __utmz=223695111.1506160772.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); push_noty_num=0; push_doumail_num=0', 'Host': 'movie.douban.com', 'Referer': 'https://movie.douban.com/top250?start=225&filter=', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36', }
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()) aa = simqueue.dequeue() print(aa) return simqueue.dequeue()
def hotpotato(nameList, num): q = Queue() for i in nameList: q.enqueue(i) while q.size() > 1: for _ in range(num): v = q.dequeue() q.enqueue(v) print(q.dequeue()) print(f"the last one is: {q.dequeue()}")
def hot_pot(names, num): # create a Queue q = Queue() _ = [q.enqueue(i) for i in names] count = 0 while q.size()!=1: while count !=num: q.enqueue(q.dequeue()) count +=1 q.dequeue() return q.dequeue()
def hotPotato(namelist,num): s = Queue() for one in namelist: s.enqueue(one) while s.size() > 1: for i in range(num): tmp = s.dequeue() s.enqueue(tmp) tmp = s.dequeue() return s.dequeue()
def HotPotato(namelist: List[str], repetitions: int) -> List[str]: queue = Queue() for name in namelist: queue.enqueue(name) for rep in range(repetitions): person = queue.dequeue() queue.enqueue(person) return queue.dequeue()
def simulation(numSeconds, pagesPerMinute): # create a new printer object labprinter = Printer(pagesPerMinute) # create a queue object printQueue = Queue() # create a list type of object, for storing all waiting times for each task waitingtimes = [] # unit is based on second, and numSeconds is the total time # for simulation, create a loop for simulation for currentSecond in range(numSeconds): # newprinttaask decides whether we want to create a new task # see detail in newPrintTask function defined later if newPrintTask(): task = Task(currentSecond) # if there is a new task, put that new task to # the end of the queue printQueue.enqueue(task) if (not labprinter.busy()) and (not printQueue.isEmpty()): # when printer is not busy or queue is empty # start to process next task from the top of the task queue nexttask = printQueue.dequeue() # meanwhile add the waiting time to the end of the time lise waitingtimes.append(nexttask.waitTime(currentSecond)) # then start the next task pop out from the queue labprinter.startNext(nexttask) # keep counting the time till the end of the task labprinter.tick() averageWait = sum(waitingtimes) / len(waitingtimes) print("Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printQueue.size()))
def murderPossibility(band, enemy, enemyX, enemyY, enemyId, enemyDirection, me, meId, distance): searchGrid = { 0: [(1, 0, 0), (0, -1, 3), (0, 1, 1)], 1: [(0, 1, 1), (1, 0, 0), (-1, 0, 2)], 2: [(-1, 0, 2), (0, 1, 1), (0, -1, 3)], 3: [(0, -1, 3), (1, 0, 0), (-1, 0, 2)] } searchList = [(enemyX, enemyY)] searchQueue = Queue() searchQueue.enqueue((enemyX, enemyY, 0, enemyDirection)) while True: currentPosition = searchQueue.dequeue() currentX = currentPosition[0] currentY = currentPosition[1] currentStep = currentPosition[2] currentDirection = currentPosition[3] if currentStep >= distance + 5: return False step = currentStep + 1 for coordinate in searchGrid[currentDirection]: horizon = currentX + coordinate[0] vertical = currentY + coordinate[1] newDirection = coordinate[2] if horizon >= 0 and horizon <= 100 and vertical >= 0 and vertical <= 101: if band[horizon][vertical] == meId and step < distance + 5: return True elif band[horizon][vertical] != enemyId and ( (horizon, vertical) not in searchList): searchQueue.enqueue( (horizon, vertical, step, newDirection)) searchList.append((horizon, vertical))
def simulation(numSeconds, pagesPerMinute): """ Simulate the printing tasks managed by the shared printer in a computer science lab. :param numSeconds: the total time for the printer to run :param pagesPerMinute: the printing speed of the printer """ 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 pig_latin_converter(word): if type(word) != str: raise TypeError('Argument should be a string') my_simulation = Queue() to_lower = word.lower() modified = list(to_lower) pos = 0 found = True if modified[0] in ['a', 'e', 'i', 'o', 'u']: return word + 'way' else: while pos <= len(word) and found: if modified[pos] in ['a', 'e', 'i', 'o', 'u']: found = False else: my_simulation.enqueue(modified[pos]) pos += 1 rounds = my_simulation.size() simulator_stack = Stack() for i in modified: simulator_stack.push(i) diff = len(word) - rounds fixed = [] for j in range(diff): fixed.append(simulator_stack.pop()) fixed.reverse() final_word = '' to_fix_with = [] while not my_simulation.isEmpty(): to_fix_with.append(my_simulation.dequeue()) final_word = ''.join(fixed) + ''.join(to_fix_with) + 'ay' return final_word
class Printer(): def __init__(self): self.printQueue = Queue() self.currentTask = None def isBusy(self): return self.currentTask == None def addTask(self, task): self.printQueue.enqueue(task) def removeTask(self): self.currentTask = None def getNextTask(self): if self.printQueue.isEmpty(): self.currentTask = None else: self.currentTask = self.printQueue.dequeue() def printTask(self): if self.currentTask != None: self.currentTask.removePage() if self.currentTask.isDone(): self.currentTask = None if self.currentTask == None and not self.printQueue.isEmpty(): self.currentTask = self.printQueue.dequeue() waitTimes.append(time - self.currentTask.startTime)
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black')
def hotPotato(namelist, num): simqueue = Queue() #create a new queue for name in namelist: simqueue.enqueue(name) while simqueue.size() > 1 : for i in range(num): simqueue.enqueue(simqueue.dequeue()) #the first in queue leaves the queue and enters again. #simqueue.dequeue() break return simqueue.dequeue()
def BFS(g,start): # 给定一幅图g和一个起始节点start,在广度优先搜索过程中遍历图中所有结点,并标记它们的距离,前驱和颜色 start.setDistance(0)#设置start结点的距离为0 start.setPred(None)#设置start结点的前驱为None VertQueue=Queue()#创建一个队列用于按保存待搜索结点 VertQueue.enqueue(start)#将start结点入队 #循环遍历所有入队的结点 while (VertQueue.size()>0): CurrentVert=VertQueue.dequeue() # 遍历当前搜索结点的所有邻居 for nbr in CurrentVert.getConnections(): #.getConnections方法返回CurrentVert的所有邻居结点 #若该邻居的颜色为白色,则其从未被搜索,对其执行入队,染色,设定距离和前驱的操作 if (nbr.getColor()=='white'): nbr.setColor('grey') nbr.setDistance(CurrentVert.getDistance()+1) nbr.setPred(CurrentVert) VertQueue.enqueue(nbr) #直至CurrentVert的结点被遍历完毕,代表其邻居结点已被完全搜索,将其颜色设为黑色 CurrentVert.setColor('black')
def simulation(numSeconds, ppm): labprinter = Printer(ppm) printq = Queue() waitingtime = [] for i in range(numSeconds): if newtask(): task = Task(i) printq.enqueue(task) if (not labprinter.busy()) and (not printq.isEmpty()): nextprint = printq.dequeue() waitingtime.append(nextprint.waittime(i)) labprinter.startnew(nextprint) labprinter.tick() averagewaittime = sum(waitingtime) / len(waitingtime) print('Average wait time %6.2f secs and %3d tasks remaining.' % (averagewaittime, printq.size()))
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.setStart(nexttask) labprinter.tick() averageWait = sum(waitingtimes) / len(waitingtimes) print("Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printQueue.size()))
def simulation(num_seconds, ppm): lab_printer = Printer(ppm) print_queue = Queue() waiting_times = [] for current_second in range(num_seconds): if new_print_task(): task = Task(current_second) print_queue.enqueue(task) if (not lab_printer.busy()) and (not print_queue.isEmpty()): next_task = print_queue.dequeue() waiting_times.append(next_task.wait_time(current_second)) lab_printer.start_next(next_task) lab_printer.tick() average_wait = sum(waiting_times) / len(waiting_times) print('Average wait %6.2f secs %3d tasks remaining.' % (average_wait, print_queue.size()))
def main(numSeconds,pagesPerMinute): labPrinter = Printer(pagesPerMinute) printQueue = Queue() watingtimes = [] for currentSeconds in range(numSeconds): if newPrintTask(): task = Task(currentSeconds) printQueue.enqueue(task) if(not labPrinter.is_busy()) and (not printQueue.isEmpty()): nexttask = printQueue.dequeue() watingtimes.append(nexttask.waitTime(currentSeconds)) labPrinter.startNew(nexttask) labPrinter.tick() averageWait = sum(watingtimes)/len(watingtimes) print('平均等待%6.2f秒 还剩%3d任务'%(averageWait,printQueue.size()))
def simulation(timeSpanSeconds, pagerate, studentnum, pages_per_task): labprinter = Printer(pagerate) waitQueue = Queue() waitTimes = [] for nth_second in range(timeSpanSeconds): if nextTask(studentnum): task = Task(nth_second, pages_per_task) waitQueue.enqueue(task) if (not labprinter.busy()) and (not waitQueue.isEmpty()): newtask = waitQueue.dequeue() waitTimes.append(newtask.waitTime(nth_second)) labprinter.setNextTask(newtask) labprinter.tick() average_wait_time = sum(waitTimes) / len(waitTimes) print("Average wait time = {:.4f}, tasks remaining = {:d}".format( average_wait_time, waitQueue.size())) return average_wait_time
def simulation(number_second, pages_per_minute): lab_printer = Printer(pages_per_minute) print_queue = Queue() wait_times = [] for current_second in range(number_second): if new_print_task(): task = Task(current_second) print_queue.enqueue(task) if (not lab_printer.busy()) and (not print_queue.isEmpty()): next_task = print_queue.dequeue() wait_times.append(next_task.wait_time(current_second)) lab_printer.start_next(next_task) lab_printer.tick() average_wait = sum(wait_times) / len(wait_times) print("Average Wait %6.2f secs %3d task remaining." % (average_wait, print_queue.size()))
def printer_simulator(num_sec, pages_per_min): printer = Printer(pages_per_min) wait_time_list = [] print_queue = Queue() for sec in range(num_sec): if new_task(): task = Task(sec) print_queue.enqueue(task) if (not printer.is_busy()) and (not print_queue.isEmpty()): next_task = print_queue.dequeue() wait_time_list.append(sec - next_task.get_timestamp()) printer.next_task(next_task) printer.tick() average_wait_time = sum(wait_time_list) / len(wait_time_list) print('average: {aver}; waiting task: {tasks}'.format( aver=average_wait_time, tasks=print_queue.size()))
def simulation(speed, totaltime): l = Line(speed) cartQueue = Queue() waitTimes = [] for i in range(totaltime): if newCart(): c = Cart(i) cartQueue.enqueue(c) if (not l.busy()) and (not cartQueue.isEmpty()): cart = cartQueue.dequeue() waitTimes.append(cart.waitTime(i)) l.startNext(cart) l.tick() avgWait = sum(waitTimes) / len(waitTimes) print( "Average wait time for each cart is %6.2f secs, %3d tasks remaining" % (avgWait, cartQueue.size()))
def simulation(numberSeconds, ppm): printer = Printer(ppm=ppm) tasks = Queue() waitingList = [] for currentTime in range(numberSeconds): if printer.isBusy(): printer.tick() else: if not tasks.isEmpty(): newTask = tasks.dequeue() printer.startNext(newTask) waitingList.append(newTask.waitTime(currentTime)) if random.randint(1, 180) == 180: task = Task(currentTime) tasks.enqueue(task) print(sum(waitingList) * 1.0 / len(waitingList))
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("平均等待时间为:%6.2f" % averageWait)
def simulateOneServer(file): """function to handle requests using one server""" global averageWait content = urllib.request.urlopen(file).read().decode( "ascii", "ignore") # fetch contents data = StringIO(content) # read csv file csv_reader = csv.reader(data, delimiter=',') dataList = [] # store data from csv for line in csv_reader: # Use list to store data dataList.append(line) requestQueue = Queue() # queue tor requests waitingtimes = [ ] # list to store's that are waiting before a request is processed server = Server() # instantiate server class # listlength=len(dataList)-1 for i in dataList: # iterated the requests request = Request(i) # pass data to request class requestQueue.enqueue(request) # enqueue the request object if (not requestQueue.isEmpty()) and (not server.busy( )): # if server is not busy and queue is not empty nexttask = requestQueue.dequeue() # dequeue first item in queue waitingtimes.append(nexttask.waitTime(int( i[0]))) # append to waiting time to list server.startNext( nexttask) # if server is free move to the next task server.tick() # server timer averageWait = sum(waitingtimes) / len( waitingtimes) # calculate average wait time print("Average Wait %6.2f secs %3d tasks remaining." % (averageWait, requestQueue.size())) # similar to pritning example in notes print("Average latency is {} seconds".format(averageWait)) return averageWait # return latency
def simulation(num_seconds, page_rate): labPrinter = Printer(page_rate) printerQueue = Queue() waitingTime = [] pages_number = 20 students_number = 10 for second in range(num_seconds): if newPrintTask(students_number): task = Task(second, pages_number) printerQueue.enqueue(task) if (not labPrinter.busy()) and (not printerQueue.isEmpty()): nextTask = printerQueue.dequeue() waitingTime.append(nextTask.waitingTime(second)) labPrinter.startNext(nextTask) labPrinter.tick() averageWait = sum(waitingTime) / len(waitingTime) print("Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printerQueue.size()))
def simulation(numSeconds, pagesPerMinute, stud): labprinter = Printer(pagesPerMinute) printQueue = Queue() waitingtimes = [] for currentSecond in range(numSeconds): if newPrintTask(stud): 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 %2.2f secs %2d tasks remaining.' % (averageWait, printQueue.size()))
f=open('url_queue.txt','r') start_url = f.readlines() f.close() #start_url = 'https://www.zomato.com/users/rajdeep-biswas-4638621' #Path to the Directory for the data to be dumped path = 'C:\Users\shoaib khan\Desktop\Tomato\Maps.Google.Com\Trajectory Mining\TryingNew\dust_bin' '''#Declaring Driver driver = webdriver.Chrome(chromedriver) #Defining Wait time over driver wait = WebDriverWait(driver,30)''' #Declaring the URL Queue url_q = Queue() users_crawled = [] def define_driver(): #Declaring Driver driver = webdriver.Chrome(chromedriver) #Defining Wait time over driver wait = WebDriverWait(driver,30) return driver,wait def driver_get(driver,url): try: driver.get(url)