Compute Courier Compensation for Delivery Trips
Math & Bit ManipulationModel answerLast updated
Calculate total delivery earnings from start/end times and distances using conditional rates, rush-hour multipliers, and precision rules.
You are building a compensation module for a logistics platform to evaluate total courier payouts across completed delivery orders.
Each delivery order is formatted as an object with three attributes:
start_time(string): The start timestamp in ISO format (e.g.,"2023-11-15T17:45:00").end_time(string): The completion timestamp in ISO format (e.g.,"2023-11-15T18:15:00").distance_km(float): The total travel distance in kilometers.
Pricing Specifications:
- Base Rate: Every trip earns a fixed base fee of $2.00.
- Mileage Fee: Add $0.50 for each completed kilometer.
- Trip Duration Surcharge:
- If the delivery duration is strictly greater than 30 minutes, append a flat delay bonus of $5.00.
- Rush Hour Surcharge:
- If the delivery starts during rush hour (18:00 to 21:00 inclusive), apply an extra 20% multiplier (1.20x) to the trip's subtotal (Base Rate + Mileage Fee + Duration Surcharge).
Instructions:
Write a function calculate_payout(deliveries) that accepts a list of delivery objects and returns the total courier payout as a float, rounded to two decimal places.
Rules & Constraints:
- All timestamps within a single test case fall on the same calendar day.
- Rush hour start condition is inclusive: any start time where
18:00:00 <= start_time <= 21:00:00qualifies. - Precision requirement: Intermediate individual trip totals must be rounded to 4 decimal places before summing them up to avoid accumulation drift.
- The returned final output must be rounded to 2 decimal places.
Example 1:
deliveries = [
{
"start_time": "2023-11-15T18:00:00",
"end_time": "2023-11-15T18:40:00",
"distance_km": 2.0
}
]
# Step-by-step:
# Base rate = 2.00
# Mileage = 2.0 * 0.50 = 1.00
# Duration = 40 minutes (> 30 mins) -> Delay fee = 5.00
# Subtotal = 2.00 + 1.00 + 5.00 = 8.00
# Rush Hour check: Starts at 18:00:00 (In range [18:00, 21:00]) -> 8.00 * 1.20 = 9.60
# Result: 9.6
Hints
Hint 1
Parse timestamps into datetime objects and calculate duration by taking their difference in minutes.
Hint 2
Separate subtotal calculation (base + distance + duration fee) from the rush hour multiplier.
Hint 3
Use Python's `decimal` module or precise intermediate rounding to 4 decimal places before computing the overall sum.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The task requires processing a list of delivery records to compute individual payout values according to tiered business logic and returning their accumulated sum.
- Parsing Timestamps: Convert ISO strings (
start_timeandend_time) to standarddatetimeobjects usingdatetime.fromisoformat. Calculate the duration in minutes by taking(end_time - start_time).total_seconds() / 60.0. - Subtotal Calculation:
- Start with a fixed base rate of
$2.00. - Add distance compensation calculated as
distance_km * 0.50. - Check if duration is strictly greater than 30 minutes (
duration > 30). If so, add a$5.00surcharge.
- Start with a fixed base rate of
- Rush Hour Check:
- Extract the time portion of
start_time. - Check if
18:00:00 <= start_time.time() <= 21:00:00. - If true, multiply the accumulated subtotal by
1.20.
- Extract the time portion of
- Precision Management:
- To prevent standard IEEE 754 floating-point inaccuracies, handle monetary calculations using Python's standard
decimal.Decimalmodule with half-up rounding. - Round each trip's payout to 4 decimal places before adding to the running sum.
- Round the final total sum to 2 decimal places.
- To prevent standard IEEE 754 floating-point inaccuracies, handle monetary calculations using Python's standard
Python Source Code
from datetime import datetime, time
from decimal import Decimal, ROUND_HALF_UP
BASE_FEE = Decimal("2.00")
PER_KM_RATE = Decimal("0.50")
DELAY_FEE = Decimal("5.00")
DELAY_THRESHOLD_MINUTES = 30
RUSH_MULTIPLIER = Decimal("1.20")
RUSH_START = time(18, 0, 0)
RUSH_END = time(21, 0, 0)
FOUR_DECIMALS = Decimal("0.0001")
TWO_DECIMALS = Decimal("0.01")
def _is_rush_hour(start_dt: datetime) -> bool:
"""Returns True if trip starts between 18:00 and 21:00 inclusive."""
return RUSH_START <= start_dt.time() <= RUSH_END
def _compute_trip_payout(trip: dict) -> Decimal:
start_dt = datetime.fromisoformat(trip["start_time"])
end_dt = datetime.fromisoformat(trip["end_time"])
if end_dt < start_dt:
raise ValueError("end_time cannot be earlier than start_time.")
distance = Decimal(str(trip["distance_km"]))
if distance < Decimal("0"):
raise ValueError("distance_km cannot be negative.")
# Base rate + mileage fee
subtotal = BASE_FEE + (distance * PER_KM_RATE)
# Duration surcharge check (> 30 minutes)
duration_seconds = (end_dt - start_dt).total_seconds()
if duration_seconds > DELAY_THRESHOLD_MINUTES * 60:
subtotal += DELAY_FEE
# Rush hour multiplier check
if _is_rush_hour(start_dt):
subtotal *= RUSH_MULTIPLIER
# Round individual trip earnings to 4 decimal places
return subtotal.quantize(FOUR_DECIMALS, rounding=ROUND_HALF_UP)
def calculate_payout(deliveries: list[dict]) -> float:
total_payout = Decimal("0.00")
for trip in deliveries:
total_payout += _compute_trip_payout(trip)
# Return overall total rounded to 2 decimal places as float
final_amount = total_payout.quantize(TWO_DECIMALS, rounding=ROUND_HALF_UP)
return float(final_amount)
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of deliveries in the input list. Parsing ISO timestamps and performing arithmetic operations on fixed-precision numbers takes $\mathcal{O}(1)$ constant time per trip.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space beyond storing the input array, as processing occurs in a single pass with scalar running variables.