
프로그래머스 - 2019 KAKAO BLIND RECRUITMENT - 오픈채팅방
1시간 + a
닉네임 변경방법에는 2가지가 존재한다.
예를 들어보면, 다음과 같다.
- Prodo님이 들어왔습니다. (uid1234, Muzi가 채팅방 들어옴)
- Ryan님이 들어왔습니다. (uid4567, Prodo가 채팅방 들어옴)
- Prodo님이 나갔습니다. (uid1234, Muzi가 닉네임을 Prodo로 바꾸고 난 후에 채팅방 나감)
- Prodo님이 들어왔습니다. (uid1234, Muzi(Prodo)가 채팅방 들어옴)
- (uid4567, Prodo가 Ryan으로 닉네임 바꿈)
즉, 가장 마지막에 정해진 닉네임으로 모든 채팅방 메시지가 변환된다.
그래서 유저 아이디를 key로 하여 (행동, 닉네임)을 저장한다. 그리고 가장 마지막에 저장된 (행동, 닉네임)에서 다음의 조건을 따져 각각의 유저 아이디에 하나의 닉네임만을 정해준다.
가장 마지막에 저장된 튜플에서 행동이 Enter거나 Change의 닉네임 = 확정 닉네임
하나의 닉네임을 각각 지정해주고 나서 Record에 나오는 순서대로 값을 반환해준다.
answer = []
users = {} # 사용자 아이디를 기준으로 (행동, 닉네임) 저장
for r in record:
splitRecord = r.split() # 공백을 기준으로 나눠줌 ("Enter", "uid1234", "Muzi")
command = splitRecord[0] # 행동
userId = splitRecord[1] # 사용자 아이디
if command == "Leave": # 행동이 Leave라면 닉네임이 주어지지 않으므로 따로 확인해준다.
if userId in users: # (행동, 닉네임) 튜플을 추가해준다.
users[userId].append((command, ""))
else:
users[userId] = [(command, "")]
else:
if userId in users:
users[userId].append((command, splitRecord[2]))
else:
users[userId] = [(command, splitRecord[2])]
record = ["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"]
users = ["uid1234" : [("Enter", "Muzi"), ("Leave", ""), ("Enter", "Prodo")], "uid4567" : [("Enter", "Prodo"), ("Change", "Ryan")]]]
위와 같이 저장된다.
nicknames = {}
for userId, action in users.items():
for command, name in reversed(action): # users에 저장된 각각의 사용자 아이디의 value인 튜플
if command == "Enter" or command == "Change": # 만약 행동이 Enter나 Change라면 닉네임 확정
nicknames[userId] = name
break
튜플을 역순으로 순회하면서 행동이 Enter나 Change인 경우에는 그때의 닉네임으로 결정짓고 for문을 탈출한다. (최신의 닉네임으로 확정짓기 위함)
nicknames에 각각의 사용자 아이디에 따라 닉네임을 저장해준다.
def msg(act, name):
if act == "Enter":
return name+"님이 들어왔습니다."
else: # act == "Leave"
return name+"님이 나갔습니다."
for output in record:
splitOutput = output.split()
if splitOutput[0] != "Change": # 행동이 Change가 아니라면,
answer.append(msg(splitOutput[0], nicknames[splitOutput[1]]))
record 순서대로 answer를 반환해야 하므로 record의 각 문자열을 output으로 받아 공백을 기준으로 split해준다.
행동이 Change가 아니라면, msg함수를 호출해준다.
msg함수
행동이 Enter라면, return name+"님이 들어왔습니다."
행동이 Leave라면, return name+"님이 나갔습니다."
def msg(act, name):
if act == "Enter":
return name+"님이 들어왔습니다."
else: # act == "Leave"
return name+"님이 나갔습니다."
def solution(record):
answer = []
users = {}
for r in record:
splitRecord = r.split()
command = splitRecord[0]
userId = splitRecord[1]
if command == "Leave":
if userId in users:
users[userId].append((command, ""))
else:
users[userId] = [(command, "")]
else:
if userId in users:
users[userId].append((command, splitRecord[2]))
else:
users[userId] = [(command, splitRecord[2])]
nicknames = {}
for userId, action in users.items():
for command, name in reversed(action):
if command == "Enter" or command == "Change":
nicknames[userId] = name
break
for output in record:
splitOutput = output.split()
if splitOutput[0] != "Change":
answer.append(msg(splitOutput[0], nicknames[splitOutput[1]]))
return answer

햅삐-😊