오픈채팅방

발자·2023년 7월 7일
0

programmers

목록 보기
34/34

틀린 코드

def solution(records):
    # 결과
    answer = []
    # ID : 닉네임
    nickname = dict()
    for record in records:
        record = record.split()
        # 채팅방 입장
        if record[0] == "Enter":
            answer.append(f"{record[1]}님이 들어왔습니다.")
            nickname[record[1]] = record[2]
        # 채팅방 퇴장
        elif record[0] == "Leave":
            answer.append(f"{record[1]}님이 나갔습니다.")
        # 닉네임 변경
        else:
            nickname[record[1]] = record[2]
    
    # 문자열로 변경
    answer = "#".join(answer)
    
    # ID => 닉네임으로 치환
    for nick in nickname.keys():
        answer = answer.replace(nick, nickname[nick])

    # 리스트로 변경
    answer = answer.split("#")
        
    return answer

이렇게 문자열로 변경하고, 다시 리스트로 변경하는 것보다는
먼저 최종적으로 수정된 닉네임을 저장하고,
그 후에 리스트로 출력하는 것이 빠르다.

정답 코드

def solution(records):
    # 결과
    answer = []
    # ID : 닉네임
    nickname = dict()
    
    # 닉네임 저장
    for record in records:
        record = record.split()
        if len(record) == 3:
            nickname[record[1]] = record[2]
    
    # 출력
    for record in records:
        record = record.split()
        # 채팅방 입장
        if record[0] == "Enter":
            answer.append(f"{nickname[record[1]]}님이 들어왔습니다.")
        # 채팅방 퇴장
        elif record[0] == "Leave":
            answer.append(f"{nickname[record[1]]}님이 나갔습니다.")
        
    return answer

0개의 댓글