Program to find average waiting time in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array customers, where customers[i] = holds a pair [arrival_i, time_i], here arrival_i is the arrival time of the ith customer. And the arrival times are sorted from less to high. And time_i is the time needed to prepare the order of the ith customer. Now, when a customer arrives, he/she gives the order, and the only that order starts preparing when the cook is idle. The cook does not prepare food for more than one customer at a time. And he prepares in order they were placed their orders. We have to find the average waiting time of all customers.

So, if the input is like customers = [[7,2],[8,4],[10,3],[20,1]], then the output will be 3.5 because,

  • The first customer came at time 7, the cook takes the order and starts preparing it immediately at time 7, and finishes at time 9, so waiting time for first customer is 9 - 7 = 2.

  • The second customer came at time 8, the chef takes his order and starts preparing it at time 9, and finishes at time 13, so the waiting time of the second customer is 13 - 8 = 5.

  • The third customer came at time 10, the chef takes his order and starts preparing it at time 13, and finishes at time 16, so the waiting time for third customer is 16 - 10 = 6.

  • The fourth customer came at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.

  • So the average waiting time = (2 + 5 + 6 + 1) / 4 = 3.5.

To solve this, we will follow these steps −

  • arr := a new list
  • time := 0
  • for each pair (i, j) in customers, do
    • if i > time, then
      • time := i + j
    • otherwise,
      • time := time + j
  • insert (time-i) at the end of arr
  • return (average of all items in arr)

Example

Let us see the following implementation to get better understanding −

def solve(customers):
   arr = []

   time = 0

   for i , j in customers:
      if(i > time):
         time = i + j
      else:
         time += j
      arr.append(time - i)

   return sum(arr) / len(arr)

customers = [[7,2],[8,4],[10,3],[20,1]]
print(solve(customers))

Input

[[7,2],[8,4],[10,3],[20,1]]

Output

3
raja
Updated on 06-Oct-2021 11:33:56

Advertisements