- 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/42888

 

문제 이해 

1. 처음 방에 들어오는거면 처음에 입력한 이름을 사용하고,

2. 이미 방에 들어온 적이 있는데 닉네임을 변경한 경우는 아이디를 식별해서 이미 입력한 문장을 변경한 이름으로 변경한다 

3. 나가는 거는 그냥 나가는 것이고

4. 이름을 변경하는 경우는 같은 아이디의 닉네임은 다 변경해야 한다 

 

처음에는 아이디는 변하지 않으므로 아이디를 키, 닉네임을 밸류로 하는 딕셔너리를 만들어서 진행해야하나 싶었다

이렇게 했을때 막혔던 부분이 그럼 enter, leave, change는 어떻게 하지? 였다 

그것 때문에 어떻게 할지 몰라서 다른 풀이를 봤는데, 위의 문제는 반복문을 한번 더 실행하면 되는 것이었다 

 

leave는 아이디를 식별할 필요가 없으므로 단어 갯수가 2개 나머지는 3개이므로 단어가 3개인 경우로 딕셔너리를 만든다

이 경우 같은 아이디가 닉네임을 변경한 경우는 마지막에는 가장 최신 값으로 저장될 것이므로 문제의도에 적절하다 

change는 따로 알림이 가지 않으므로 이는 출력할 필요가 없고, enter인지 leave인지에 따라 나눠서 출력하면 정답이다 

 

놓친 것들

이름 변경할 때는 문장을 출력하지 않는다 

enter / change는 단어가 3개이지만, leave는 2개이다 

 

- 정답 풀이 :

def solution(record):
    answer = []
    dic = {}
   
    for sentence in record:
        sentence_split = sentence.split()
        #Leave의 단어는 2개이기 때문에 이걸 구별하는 분기문
        if len(sentence_split) == 3:
            dic[sentence_split[1]] = sentence_split[2]
            
    for sentence in record:
        sentence_split = sentence.split()
        #change는 따로 문장을 출력하지 않는다 
        if sentence_split[0] == 'Enter':
            answer.append('{}님이 들어왔습니다.'.format(dic[sentence_split[1]]))
        elif sentence_split[0] == 'Leave':
            answer.append('{}님이 나갔습니다.'.format(dic[sentence_split[1]]))
            
    return answer

- 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/118667

 

 

부족했던 부분 

1. queue에 deque() 설정 안한 것 (시간초과 발생)

2. sum을 반복문마다 설정한 것 (시간초과 발생)

3. -1이 출력되는 경우에 대해 파악이 잘 되지 않았다 (11번, 28번 테스트에서 틀림)

 

참고한 블로그

 

- 정답 풀이 :

queue의 합만 기록하면 되고, 둘의 합이 같을 때니까 sum(queue1)만 가지고 진행하면 된다. (one == half 일 때, one == two 니까) 

따라서 굳이 queue2 가지고 연산할 필요가 없고, queue1가지고만 진행하면 된다 

from collections import deque
def solution(queue1, queue2):
    queue1, queue2 = deque(queue1), deque(queue2)
    one = sum(queue1)
    half = (one + sum(queue2)) // 2
    
    answer = 0 
    while queue1 and queue2:                       
        if one == half:
            return answer
        if one > half:
            one -= queue1.popleft()
        elif one < half:    
            x = queue2.popleft()
            queue1.append(x)
            one += int(x)
        answer += 1
        
    return -1

 

- 시도한 풀이 1:

63퍼센트에서 틀렸다 

 

틀린 이유

1. queue문제는 무조건 deque() 이용해서 풀어야한다

2. sum은 반복문 바깥에서 한번만 해야한다. 

-> 1, 2번 안 해서 시간초과 오류가 떴다 

def solution(queue1, queue2):    
    count = sum(queue1)* 2 - 1
    half = (sum(queue1) + sum(queue2)) / 2
    
    answer = 0 
    while True:
        one = sum(queue1)
        two = sum(queue2)
        if count == 0 and one != half:
            answer = -1
            break           
        if one == half:
            break
        if one > two:
            queue2.append(queue1.pop(0))
        elif one < two:
             queue1.append(queue2.pop(0))
        count -= 1
        answer += 1
        
    return answer

 

- 시도한 풀이 2 :

위 풀이에서 deque로 바꿔주고 sum을 한번하one, two에 연산하는 걸 추가했고, 93.3에서 틀렸다. 테스트 11, 28에서 시간초과가 났다 

정답 풀이와 비교해보면 queue1,2의 합을 이용하는 것과 queue2까지 사용해서 시간초과가 난 것 같기도 하다,,, (사실 잘 모르겠다)

 

예제를 통해서 -1이 출력되는 경우는 2 * half -1 까지 돌았는데도 두 큐의 합이 같지 않은 경우라고 생각해서 

count를 이용했지만 11번, 28번에서 계속 에러가 났다 

from collections import deque
def solution(queue1, queue2):
    queue1, queue2 = deque(queue1), deque(queue2)
    one, two = sum(queue1), sum(queue2)
    count = sum(queue1)* 2 - 1
    half = (sum(queue1) + sum(queue2)) / 2
    
    answer = 0 
    while True:        
        if count == 0 and one != half:
            answer = -1
            break           
        if one == half:
            break
        if one > two:
            x = queue1.popleft()
            two += x
            one -= x
            queue2.append(x)
        elif one < two:
            x = queue2.popleft()
            one += x
            two -= x            
            queue1.append(x)
        count -= 1
        answer += 1
        
    return answer

- 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/17682

 

- 정답 풀이 :

def solution(dartResult):
    answer = []
    index = 0
    score_idx = -1
    
    while index < len(dartResult):
        if dartResult[index].isdigit():
            end_index = index
            #두 자리 수가 있는 경우에 대비해서
            while dartResult[end_index].isdigit():
                end_index += 1
            if dartResult[end_index] == 'S':
                answer.append(int(dartResult[index:end_index]))
            elif dartResult[end_index] == 'D':
                answer.append(int(dartResult[index:end_index]) ** 2)
            elif dartResult[end_index] == 'T':
                answer.append(int(dartResult[index:end_index]) ** 3)
                
            score_idx += 1
            index = end_index + 1
            
        else:
            if dartResult[index] == '*':
                if score_idx == 0 :
                    answer[score_idx] *= 2
                else:
                    answer[score_idx - 1] *= 2
                    answer[score_idx] *= 2
            elif dartResult[index] == '#':
                answer[score_idx] *= -1
                
            index += 1
            
    return sum(answer)

- 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/12940

 

- 정답 풀이: 

 

def solution(n, m):
    mcd = 0
    for i in range(1, max(n,m) + 1):
        if n % i == 0 and m % i == 0:
            mcd = max(mcd, i)
    if mcd == 1: 
        return [1, n * m]
    else:
        return [mcd, mcd * (n // mcd) * (m // mcd)]

 

- 다른 풀이 :

Euclidean Algorithm을 구현한 풀이다

def gcdlcm(a, b):
    c, d = max(a, b), min(a, b)
    t = 1
    while t > 0:
        t = c % d
        c, d = d, t
    answer = [c, int(a*b/c)]

    return answer

# 아래는 테스트로 출력해 보기 위한 코드입니다.
print(gcdlcm(3,12))

+ Recent posts