Search code examples
pythonpython-3.xpython-gstreamer

Find average duration of a successful delivery in Python


I am required to write a function in Python 3 to calculate the average delivery times of a successful delivery.

Let me explain,

A mobile application will send me a dictionary every time a food delivery order is placed in this format. {'OrderID':1,'Current Stage':1, 'Customer':101,'OrderTime': 12:32:10}

when the delivery driver accepts the order a new record will be generated. {'OrderID':1,'Current Stage':2, 'Customer':101,'OrderTime': 12:35:30}

When the driver picks up the order from the restaurant a new record will be generated and sent like this. {'OrderID':1,'Current Stage':3, 'Customer':101,'OrderTime': 12:42:10}

When the driver delivers the order we receive the final record for this order like this {'OrderID':1,'Current Stage':4, 'Customer':101,'OrderTime': 13:02:30}

See for this order, it took 30 min to deliver the order successfully.

If another customer places the order we receive similar type of requests from the mobile app.

Some orders will be successful and some won't. Every successful order will have 4 lines sent to (but not all at a time. It's a streaming app and it delivers the line whenever a step is completed in the delivery process).

Now if another order completed successfully, and it took 40 min...then the average will be 35 min.

After the third successful order (if it took 50min) then the average would become 40 min.

For 4th successful order (if it took only 10 min) then the average would become 30 min.

So basically my function should return this average time. The input of the function is the dictionary.

Could I get some help on this please?


Solution

  • If you need to return the average of all the deliveries, then you must store the current average, and the number of successful deliveries so far as a global variable, outside your function. You should also store a dictionary, which will have the OrderID as a key, and the OrderTime (of when the order is placed), stored globally.

    This way, when you receive a request, if it's in stage 1, you store the time in the dictionary, and return the current average. If it's in stage 4, you check the global dictionary to check when this order was placed, and update the new average.