From diagram to code
After this: Read the parking lot's code class by class, run it, and work out a fee by hand.
On this page · 7 sections · 3 checks
Lesson 3 drew the plan: ten boxes and ten lines. Now you write it. Each box becomes a class, each field becomes a value the constructor stores, and each method line becomes a method, as in "Reading and drawing class diagrams". The whole program is about 150 lines in Python and 200 in Java, so this lesson shows it in three parts, from the smallest classes up to the lot.
Part 1: sizes, vehicles and spots
from abc import ABC, abstractmethodfrom enum import IntEnum
class Size(IntEnum): SMALL = 1 MEDIUM = 2 LARGE = 3
class Vehicle(ABC): def __init__(self, plate): self.plate = plate
@abstractmethod def size(self): ...
@abstractmethod def rate(self): ...
class Bike(Vehicle): def size(self): return Size.SMALL
def rate(self): return 10
class Car(Vehicle): def size(self): return Size.MEDIUM
def rate(self): return 20
class Truck(Vehicle): def size(self): return Size.LARGE
def rate(self): return 50
class Spot: def __init__(self, spot_id, size): self.spot_id = spot_id self.size = size self.vehicle = None
def is_free(self): return self.vehicle is None
def fits(self, v): return self.is_free() and v.size() <= self.size
def assign(self, v): self.vehicle = v
def release(self): self.vehicle = Noneenum Size { SMALL, MEDIUM, LARGE }
abstract class Vehicle { final String plate;
Vehicle(String plate) { this.plate = plate; }
abstract Size size();
abstract int rate();}
class Bike extends Vehicle { Bike(String plate) { super(plate); }
Size size() { return Size.SMALL; }
int rate() { return 10; }}
class Car extends Vehicle { Car(String plate) { super(plate); }
Size size() { return Size.MEDIUM; }
int rate() { return 20; }}
class Truck extends Vehicle { Truck(String plate) { super(plate); }
Size size() { return Size.LARGE; }
int rate() { return 50; }}
class Spot { final String id; final Size size; private Vehicle vehicle;
Spot(String id, Size size) { this.id = id; this.size = size; }
boolean isFree() { return vehicle == null; }
boolean fits(Vehicle v) { return isFree() && v.size().compareTo(size) <= 0; }
void assign(Vehicle v) { vehicle = v; }
void release() { vehicle = null; }}- Size is the enum. In Python it is an IntEnum: each value is also a number (1, 2, 3), so two sizes can be compared with < and <=.In Java it is an enum: compareTo puts the values in the order they are written, SMALL first.
- Vehicle is abstract, with two methods and no code in them. Each child returns its own size and its own rate in rupees per hour.
- Spot starts with no vehicle (Nonenull). is_freeisFree says whether that is still true.
- fits is one line, and it holds the rule "a vehicle may use a bigger spot": the spot must be free, and the vehicle's size must be at most the spot's size. A bike fits a small, medium or large spot; a truck fits only a large one.
- assign and release put a vehicle on the spot and take it off.
Part 2: levels, tickets and the fee rule
class Level: def __init__(self, number, spots): self.number = number self.spots = spots
def find_spot(self, v): best = None for spot in self.spots: if spot.fits(v) and (best is None or spot.size < best.size): best = spot return best
class Ticket: def __init__(self, ticket_id, vehicle, spot, entry): self.ticket_id = ticket_id self.vehicle = vehicle self.spot = spot self.entry = entry
class FeeCalculator: def fee(self, ticket, exit_minute): minutes = exit_minute - ticket.entry hours = max(1, (minutes + 59) // 60) return hours * ticket.vehicle.rate()class Level { final int number; final List<Spot> spots;
Level(int number, List<Spot> spots) { this.number = number; this.spots = spots; }
Spot findSpot(Vehicle v) { Spot best = null; for (Spot spot : spots) { if (spot.fits(v) && (best == null || spot.size.compareTo(best.size) < 0)) { best = spot; } } return best; }}
class Ticket { final int id; final Vehicle vehicle; final Spot spot; final int entry;
Ticket(int id, Vehicle vehicle, Spot spot, int entry) { this.id = id; this.vehicle = vehicle; this.spot = spot; this.entry = entry; }}
class FeeCalculator { int fee(Ticket t, int exitMinute) { int minutes = exitMinute - t.entry; int hours = Math.max(1, (minutes + 59) / 60); return hours * t.vehicle.rate(); }}- find_spotfindSpot goes through every spot on the level and keeps the best one so far: a spot that fits and is smaller than the best one found before. At the end it returns the best, or Nonenull if nothing fits. Because the test is "smaller than", not "smaller or equal", the first of two spots of the same size wins.
- Ticket only holds four values: its number, the vehicle, the spot and the entry minute.
- fee works out the minutes stayed, turns them into started hours, and multiplies by the vehicle's rate.
The hours line needs a closer look. Whole-number division by 60 rounds down, so the line adds 59 first, which makes any part of an hour count as a full one. Three cases:
| Minutes stayed | Plus 59 | Divided by 60 | At least 1 | Car pays |
|---|---|---|---|---|
| 61 | 120 | 2 | 2 | 40 |
| 60 | 119 | 1 | 1 | 20 |
| 0 | 59 | 0 | 1 | 20 |
Watch the fee rule
The trace below runs the rule as a plain function with three stays: a bike for 45 minutes, a car for 61 and a car for 150. It writes "at least 1" as an if test, which does the same job as the larger-of-two call above. The task asks you to watch hours in each call.
- Run the programRun it and step through the three calls. In each one, watch the value of hours after the first line of the function: 1 for 45 minutes, 2 for 61 minutes, 3 for 150 minutes. The test for less than 1 is never true here, because every stay is longer than zero minutes.
def fee(minutes, rate): hours = (minutes + 59) // 60 if hours < 1: hours = 1 return hours * rate
print(fee(45, 10))print(fee(61, 20))print(fee(150, 20))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Part 3: the lot
class ParkingLot: def __init__(self, levels, fees): self.levels = levels self.fees = fees self.active = {} self.next_id = 1
def park(self, v, minute): for level in self.levels: spot = level.find_spot(v) if spot is not None: spot.assign(v) ticket = Ticket(self.next_id, v, spot, minute) self.active[ticket.ticket_id] = ticket self.next_id += 1 print(f"ticket {ticket.ticket_id}: {v.plate} -> {spot.spot_id} (level {level.number})") return ticket print(f"no spot for {v.plate}") return None
def unpark(self, ticket_id, minute): ticket = self.active.pop(ticket_id) fee = self.fees.fee(ticket, minute) ticket.spot.release() print(f"{ticket.vehicle.plate} leaves {ticket.spot.spot_id}, {minute - ticket.entry} min, pays {fee}") return fee
def free_count(self, size): count = 0 for level in self.levels: for spot in level.spots: if spot.is_free() and spot.size == size: count += 1 return countclass ParkingLot { private final List<Level> levels; private final FeeCalculator fees; private final Map<Integer, Ticket> active = new HashMap<>(); private int nextId = 1;
ParkingLot(List<Level> levels, FeeCalculator fees) { this.levels = levels; this.fees = fees; }
Ticket park(Vehicle v, int minute) { for (Level level : levels) { Spot spot = level.findSpot(v); if (spot != null) { spot.assign(v); Ticket ticket = new Ticket(nextId, v, spot, minute); active.put(ticket.id, ticket); nextId += 1; System.out.println("ticket " + ticket.id + ": " + v.plate + " -> " + spot.id + " (level " + level.number + ")"); return ticket; } } System.out.println("no spot for " + v.plate); return null; }
int unpark(int ticketId, int minute) { Ticket ticket = active.remove(ticketId); int fee = fees.fee(ticket, minute); ticket.spot.release(); System.out.println(ticket.vehicle.plate + " leaves " + ticket.spot.id + ", " + (minute - ticket.entry) + " min, pays " + fee); return fee; }
int freeCount(Size size) { int count = 0; for (Level level : levels) { for (Spot spot : level.spots) { if (spot.isFree() && spot.size == size) { count += 1; } } } return count; }}- park asks each level in order for a spot. On the first level that has one, it puts the vehicle there, makes a ticket with the next number, stores the ticket in
activeunder its number, prints a line and returns the ticket. If no level has a spot, it printsno spot forand the plate. - unpark takes the ticket out of
activeby its number, asks the fee rule for the fee, frees the spot, prints a line and returns the fee. pop removes the entry from the dict and returns it.remove takes the entry out of the map and returns it. - free_countfreeCount goes through every spot on every level and counts the free ones of the size it was given.
Run it
Python runs in the browser when you press Run on the block below. Java does not run here: if you are learning Java, the block below shows the whole Java file to read. Paste it into a Java tool on your computer to run it.
The last lines build a small lot: level 1 has two small and two medium spots (S1, S2, M1, M2), and level 2 has one medium and one large (M3, L1). Then vehicles arrive and leave at set minutes. Three of them leave and pay 10, 40 and 60 rupees, so the program prints collected 110. At the end one small spot, one medium spot and no large spot are free: free 1 1 0. Lesson 5 follows these events one at a time.
Check yourself
A car arrives. Spot S1 is small and free. What does S1's fits method return for the car, and why?
Complete the missing line of the fee method. It must count every started hour, and at least one hour.
class FeeCalculator: def fee(self, ticket, exit_minute): minutes = exit_minute - ticket.entry ____________________ # ← whole started hours, at least 1 return hours * ticket.vehicle.rate()class FeeCalculator { int fee(Ticket t, int exitMinute) { int minutes = exitMinute - t.entry; ____________________ // ← whole started hours, at least 1 return hours * t.vehicle.rate(); }}The classes are the parking lot's. A car enters at minute 100 and leaves at minute 161. What does this print?
fees = FeeCalculator()ticket = Ticket(1, Car("C9"), Spot("M9", Size.MEDIUM), 100)print(fees.fee(ticket, 161))FeeCalculator fees = new FeeCalculator();Ticket ticket = new Ticket(1, new Car("C9"), new Spot("M9", Size.MEDIUM), 100);System.out.println(fees.fee(ticket, 161));How far this code goes
- Write each box of the diagram as a class, from the smallest (Size, the vehicles, Spot) up to the lot, and say in one sentence what each class is for.
- Read fits as the one line that holds the rule 'a vehicle may use a bigger spot': free, and the vehicle's size at most the spot's.
- Work out a fee by hand: minutes stayed, plus 59, divided by 60 as a whole number, at least 1, times the rate.
- Run the whole program and read its last two lines: collected 110 and free 1 1 0.
- Say why searching every spot is fine for six spots, and what a large lot would keep ready instead.