반응형
250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 정보처리기사 실기 시험
- 자료구조
- BOJ
- 프로그래머스
- it
- 백준 N-Queens
- 백준 토마토 파이썬
- 백준 백트랙킹 파이썬
- 자바
- BFS
- 코드
- 백준 백트랙킹
- 2022년 정보처리기사 실기 1회 가답안
- 토마토
- 백준 그래프 이론 파이썬
- 그리디
- 2022년 정보처리기사 실기
- 정보처리기사
- 정보처리기사 실기
- dfs
- 파이썬
- 백준 그래프 탐색 파이썬
- python
- 2022년 정보처리기사 실기 가답안
- 코딩테스트
- 프로그래밍
- 코딩
- 프로그래머스 파이썬
- 백준
- 알고리즘
Archives
- Today
- Total
코딩,안되면 될때까지
2.오픈채팅방 본문
728x90
반응형
<문제>
https://programmers.co.kr/learn/courses/30/lessons/42888
<풀이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