267. Python Program to Give Each Food Order to the Nearest Rider
HardPhase 3 · Challenge
This one takes a few steps. It uses only lists, loops, if and split(), which you know. Draw the riders of Example 1 on squared paper first.
Overview
Food delivery apps decide in a moment which rider takes each order. The simplest rule is to pick the nearest rider who is free. This is a small version of that program.
Problem Statement
Ahmed runs a small delivery app. The city is a grid of streets, and every place has an x and a y number. The input has one line per rider or order, and the last line is end:
rider <name> <x> <y>: a rider waits at this place.order <x> <y>: a new order at this place. Orders are numbered from 1.
The distance from a rider to an order is the number of blocks the rider rides: the steps left or right, plus the steps up or down. To work it out, take the difference of the two x numbers. If it is negative, drop the minus sign. Do the same for y, then add the two. For example, from 1 1 to 4 5 the distance is 3 + 4 = 7.
The rules for each order:
- The order goes to the free rider with the smallest distance.
- If two or more free riders tie, the rider who was listed first gets it.
- A rider takes only one order. After that, the rider is busy until the end.
For each order, print Order <n>: <name>, distance <d>. If no rider is free, print Order <n>: No rider free.
After end, print Free riders: and the names of the riders who are still free, in the order they were listed, with a comma and a space between them. If none are free, print Free riders: none.
Examples
Example 1. Input:
rider Ana 0 0
rider Ben 5 5
rider Chen 2 8
order 1 1
order 4 6
order 0 0
order 3 3
end
gives:
Order 1: Ana, distance 2
Order 2: Ben, distance 2
Order 3: Chen, distance 10
Order 4: No rider free
Free riders: none
Why: Ana is nearest to order 1. Ana is then busy, so order 3 at 0 0 goes to Chen, the only free rider: 2 + 8 = 10. By order 4, all 3 riders are busy.
Example 2. Input:
rider Dina 2 2
rider Eli 4 4
rider Fay 3 1
order 3 3
end
gives:
Order 1: Dina, distance 2
Free riders: Eli, Fay
Why: all 3 riders are at distance 2 from 3 3. Dina was listed first, so Dina gets the order.
Input
One rider or order per line, in the formats above, then a last line end. All the riders come before the orders. Names are single words, and every x and y is a whole number from 0 to 100. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line per order, then the Free riders: line. The tests try 7 different inputs, also an order with no riders at all, no orders at all, a rider at distance 0, and a rider who is nearer but listed later.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.