본문 바로가기
Algorithm/프로그래머스

[프로그래머스] - 오픈채팅방 (파이썬)

by 2HS 2022. 2. 15.
# 오픈채팅방
uuid = dict()
id_name = dict()


def solution(record):
    answer = []
    i = 0
    for str in record:
        if str.split()[0] == 'Leave':
            type, id = str.split()
            name = id_name[id]
            answer.append([name, '님이 나갔습니다.'])
            uuid[id].append(i)
            i += 1
        else:
            type, id, name = str.split()
            id_name[id] = name
            if type == 'Enter':
                if uuid.get(id):
                    id_name[id] = name
                    change(id, name, answer)
                    uuid[id].append(i)
                else:
                    uuid[id] = [i]
                answer.append([name, '님이 들어왔습니다.'])
                i += 1
            else:
                change(id, name, answer)
                id_name[id] = name
                # 닉네임 바꿈
    result = []
    for x in answer:
        result.append(x[0]+x[1])
    return result


def change(id, name, answer):
    for x in uuid[id]:
        answer[x][0] = name

 

2019 카카오 블라인드 - 1번

uuid = { id1 : [0, 4, 5], id2 : [1, 2, 6], id3 : [3] } : 해당 아이디로 남긴 answer의 인덱스 값을 저장 해준다.

id_name = { id1: 'Muzi', id2: 'Lion' } : 해당 아이디의 닉네임을 저장 해준다.

1. change : answer에서 해당 id가 남긴 기록의 닉네임을 현재 닉네임으로 교체

2. 가장 앞의 단어가 Leave일 경우는 split시 2개, 나머지는 split시 3개로 나뉨. Leave일 때와 아닐 때로 나눈다.

3. Leave 일때, 닉네임 업데이트, answer에 append, uuid에 index append, change함수

4. Enter 일때, uuid에 id가 없으면 새로운 값 추가, 있으면 change함수, answer에 append, uuid에 index append

5. Change 일때, answer에 추가할 필요없이 change함수