코딩,안되면 될때까지

2.오픈채팅방 본문

프로그래머스/프로그래머스-파이썬

2.오픈채팅방

soo97 2022. 1. 13. 15:12
728x90
반응형

<문제>

https://programmers.co.kr/learn/courses/30/lessons/42888

 

코딩테스트 연습 - 오픈채팅방

오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오

programmers.co.kr

<풀이1>

-접근방법 : 

1)사전자료형에 user_id와 name을 저장한다.

2)answer배열을 만을어서 각 명령어의 결과를 저장한다.

3)user_id가 name을 바꿔서 들어올 경우에 대비해 사전자료형에 user_id의 위치를 저장해놓는다.

def solution(record):
  answer = []
  dic = {}
  command1 = []

  for i in record:
    temp = i.split()
    command = temp[0]
    user_id = temp[1]
    if len(temp) == 3:
      name = temp[2]

    if command == 'Enter':
      if user_id not in dic:
        dic[user_id] = name
        answer.append("{}님이 들어왔습니다.".format(name))
        dic[user_id] = [name,[len(answer)-1]]
      else:
        if name!=dic[user_id][0]:
          t_l = len(dic[user_id][0])
          for idx in dic[user_id][1]:
            answer[idx] = name + answer[idx][t_l:]
          dic[user_id][0]= name 
          answer.append("{}님이 들어왔습니다.".format(name))
          dic[user_id][1].append(len(answer)-1)
        else:
          answer.append("{} 님이 들어왔습니다.".format(name))
          dic[user_id][1].append(len(answer)-1)

    elif command =='Leave':
        answer.append("{}님이 나갔습니다.".format(dic[user_id][0]))
        dic[user_id][1].append(len(answer)-1)
    if command =='Change':
        t_l = len(dic[user_id][0])
        dic[user_id][0] = name 
        for idx in dic[user_id][1]:
          answer[idx] = name+answer[idx][t_l:]
 
        



       
    
        
  return answer
print(solution(["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"]))

하지만 이렇게 풀경우 코드도 복잡하고 새로운 이름이 들어올때마다 answer를 갱신해주는 방식이 너무 복잡하다.(새로운 이름의 길이를 구해서 그 이후부터의 문자열과 새로운 이름을 연결해줘야 하고 사전자료형의 이름도 갱신해줘야하기 때문) 이러한 이유로 이런 방식으로 풀때 시간초과가 발생했다.

 

<풀이2>

중간결과를 answer에 저장하는게 아닌 command1에 저장한다.(ex : command1.append([temp[1],"님이 들어왔습니다.")

이러면 반복문으로 record의 원소를 하나하나 돌때마다 갱신하는 대신 한번에 최종결과를 answer에 저장할수 있다!

def solution(record):
    answer = []
    dic = {}
    command1=[]
    

    for i in record:
        temp = i.split()
        if temp[0] == "Leave":
            command1.append([temp[1],"님이 나갔습니다."])
        elif temp[0] == "Enter":
            dic[temp[1]]=temp[2]
            command1.append([temp[1],"님이 들어왔습니다."])
        elif temp[0] == "Change":
            dic[temp[1]] = temp[2]
    for command in command1:
        answer.append(dic[command[0]]+command[1])  #command[0]=temp[1]이므로 answer에 change의 결과가 반영된다.!

<정리>

1.처음 풀때 change의 결과를 반영하는부분에서 어려움을 겪음

2. 사전자료형(dic[user_id]=name)에 answer배열에서의 user_id의 위치를 저장하는 방법 사용->시간초과

3. 중간결과를 command1결과에 저장한후 최종결과를 answer배열에 저장!!

 

 

 

 

728x90
반응형

'프로그래머스 > 프로그래머스-파이썬' 카테고리의 다른 글

[프로그래머스]-괄호변환  (4) 2022.03.12
무지의 먹방 라이브  (0) 2022.02.26
조이스틱  (0) 2022.02.26
타겟넘버  (0) 2022.02.26
1.문자열 압축  (0) 2022.01.12
Comments