import math
def solution(fees, records):
answer = []
b_time, b_cost, u_time, u_cost = fees
db = {}
for r in records:
key = r[6:10]
time = int(r[0:2] + r[3:5])
time = time // 100 * 60 + time % 100
IN = True if r[-2:] == 'IN' else False
if key not in db.keys() and IN:
db[key] = (0, time, IN)
elif IN:
db[key] = (db[key][0], time, IN)
else:
db[key] = (db[key][0] + time - db[key][1], time, IN)
for key, (total, time, IN) in db.items():
if IN:
db[key] = (total + 23 * 60 + 59 - time, time, False)
total = db[key][0]
if total <= b_time:
db[key] = b_cost
else:
db[key] = b_cost + math.ceil((total - b_time) / u_time) * u_cost
for _, v in sorted(db.items(), key=lambda x: x[0]):
answer.append(v)
return answer
피드백
- 문자열 슬라이싱이 아닌
sort()
함수를 사용하라!
math.ceil
함수를 사용하여 올림을 할 수 있다
- IN OUT을 bool로 처리하기보다 'IN', 'OUT' 형태로 받자. bool로 관리하고 싶으면 define 이라도 해둘 것!
- 튜플로 만들기보다 차라리 클래스로 만드는게 나을수도?
defaultdict
를 사용하자
개선
import math
def solution(fees, records):
answer = []
db = {}
b_time, b_cost, u_time, u_cost = fees
for r in records:
time, key, IO = r.split()
h, m = time.split(':')
time = int(h) * 60 + int(m)
if key not in db.keys() and IO == 'IN':
db[key] = (0, time, IO)
elif IO == 'IN':
db[key] = (db[key][0], time, IO)
else:
db[key] = (db[key][0] + time - db[key][1], time, IO)
for key, (total, time, IO) in db.items():
if IO == 'IN':
db[key] = (total + 23 * 60 + 59 - time, time, False)
total = db[key][0]
if total <= b_time:
db[key] = b_cost
else:
db[key] = b_cost + math.ceil((total - b_time) / u_time) * u_cost
for _, v in sorted(db.items()):
answer.append(v)
return answer