Program to design parking system in Python


Suppose you want to design a parking system. A parking lot has three different kinds of parking spaces − big, medium, and small. And there are fixed number of slots for each size. Make a class called OurParkingSystem with of two methods −

  • constructor(big, medium, small) − This constructor is taking the number of slots available for different spaces and initializes object of the OurParkingSystem class.

  • addCar(carType) − This method checks whether there is a parking space of given carType for the car that wants to put inside the parking lot.

The three slots big, medium, or small, are represented by 1, 2, and 3 respectively. The constraint is a car can only park in a parking space if carType is matched. If there is no space available, return false, otherwise park the car in that size space and return true.

If there are 2 spaces for big car, no space for medium car and 1 space for small car, then constructor call will be like OurParkingSystem(2, 0, 1), and if we call addCar like −

addCar(3) − add one small car and return true

addCar(2) − No space to add medium car so return false

addCar(3) − No space to add a new small car so return false

addCar(1) − add one big car and return true

addCar(1) − add another big car and return true

addCar(1) − No space for another big car so return false

To solve this, we will follow these steps −

  • Define a function constructor() . This will take big, medium, small

  • sp := a list like [0,big,medium,small]

  • Define a function addCar() . This will take carType

  • if sp[carType] > 0, then

    • sp[carType] := sp[carType] - 1

    • return True

  • return False

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class OurParkingSystem:
   def __init__(self, big, medium, small):
      self.sp = [0,big,medium,small]

   def addCar(self, carType):
      if(self.sp[carType] >0 ):
         self.sp[carType] -= 1
         return True
      return False

ps = OurParkingSystem(2, 0, 1)
print(ps.addCar(3))
print(ps.addCar(2))
print(ps.addCar(3))
print(ps.addCar(1))
print(ps.addCar(1))
print(ps.addCar(1))

Input

ps.addCar(3)
ps.addCar(2)
ps.addCar(3)
ps.addCar(1)
ps.addCar(1)
ps.addCar(1)

Output

True
False
False
True
True
False

Updated on: 17-May-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements