Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the ParkingSystem class:
ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.Example 1:
Input
["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
[[1, 1, 0], [1], [2], [3], [1]]
Output
[null, true, true, false, false]
Explanation
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
Constraints:
0 <= big, medium, small <= 1000carType is 1, 2, or 31000 calls will be made to addCarclass ParkingSystem(object):
def __init__(self, big, medium, small):
self.carTypes = {}
self.carTypes[1] = big
self.carTypes[2] = medium
self.carTypes[3] = small
def addCar(self, carType):
if self.carTypes[carType] > 0:
self.carTypes[carType] = self.carTypes[carType] - 1
return True
else:
return False
what?
self는 객체 인스턴스로 자기자신을 참조하는 매개 변수이다.
메소드에서 첫번째 인자로 파이썬에서 self를 자동으로 넘겨준다. 아무 인자를 추가하지 않아도 self는 넘겨준다.
파이썬은 클래스의 메소드를 정의할 때 self를 명시하며, 이걸 메소드에 안보이게 전달하지만, 메소드를 불러올 때 self는 자동으로 전달된다.
how?
self를 사용함으로 클래스 내에 정의한 멤버에 접근할 수 있게된다.
what?
딕셔너리는 key:value로 매칭해서 값을 저장한다.
how?
특정 Key 값을 찾아야할 때는 리스트보다 딕셔너리가 유용하다.
배열, 튜플, 딕셔너리 선언 방법
배열, 튜플, 딕셔너리 선언 방법을 비교해서 알아두자.
| 배열[Array] | 튜플(Tuple) | 딕셔너리{Dictionary} | |
|---|---|---|---|
| 선언 | arr = [] | tup = () | dic = {} |
| 초기화 | arr = [1, 2, 3, 4] | tup = (1, 2, 3, 4) | dic = {"january":1, "February": 2, "March":3 } |
| 불러오기 | arr[0] | tup[0] | dic["March"] |
# 삽입 방법1
>>> a = {1: 'a'}
# 삽입 방법2
>>> a[2] = 'b'
>>> a
{1: 'a', 2: 'b'}
# 리스트도 value로 추가 가능
>>> a['name'] = [1,2,3]
>>> a
{1: 'a', 2: 'b', 'name': [1, 2, 3]}
# 삭제
>>> del a[1]
>>> a
{2: 'b', 'name': [1, 2, 3]}