We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defminimumAverage(customers):# Customers is a list of tuples. I assume it's already# sorted by i[0], the arrival time, but let's make sure.# We'll also need to know the total customer number in# order to calculate the average wait later on.customers.sort()cust_count=len(customers)# Since the minimum average wait will always be reached# by preparing the quickest pizza first, we want to store# the pizzas in a min heap sorted by required cook time.# As we start cooking, we'll pull customers off the list# and put them into a heap of waiting customers. We'll# also need to track time throughout the process to know# when to add to the heap or remove from it. And since# we're calculating average using the total number of# customers, we need a variable for total wait time to# divide by it.waiting=[]time=0wait_time=0# This whole process will run until there are no more# customers in either list.whilecustomersorwaiting:# Move customers to waiting once they've ordered.# Flip tuple values for correct priority sort.whilecustomersandtime>=customers[0][0]:t_order,t_cook=customers.pop(0)heapq.heappush(waiting,(t_cook,t_order))# If we're waiting for orders, jump to the next.iflen(waiting)==0:time=customers[0][0]continue# We don't want to move one second at a time as# that would confuse priority. We want to think# of time in the form of pizzas cooked. So,# instead of incrementing time, we'll add the# cook time of the highest priority pizza, one at# a time. That will give the time the customer is# served, from which we subtract their order time# to know their wait and add it to the total wait.cook,order=heapq.heappop(waiting)time+=cookwait_time+=(time-order)# Use // to return only the integer part of avg time.returnwait_time// cust_count
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Average Waiting Time
You are viewing a single comment's thread. Return to all comments →
Python3 solution with explanation!