본문 바로가기

개발일지/TIL

TIL 23-04-09

1. 프로그래머스 입문 - A로 B 만들기 

 문제점

문자열 before와 after가 매개변수로 주어질 때,
before의 순서를 바꾸어 after를 만들 수 있으면 1을,
만들 수 없으면 0을 return 하도록 solution 함수를 완성해보세요.

# dictionary로 만들어서 value의 숫자를 세고 일치하면 1, 아니면 0

 시도해 본 것들

def solution(before, after):
    # dictionary로 만들어서 value의 숫자를 세고 일치하면 1, 아니면 0
    after_dict = {}
    before_dict = {}
    for i in before:
        if i not in before_dict:
            before_dict[i] = 1
        elif i in before_dict:
            before_dict[i] += 1

    for i in after:
        if i not in after_dict:
            after_dict[i] = 1
        elif i in after_dict:
            after_dict[i] += 1

    for i in after_dict.keys():
        if before_dict[i] != after_dict[i]:
            return 0
    return 1

결과는 대부분 맞지만, 어느 한 경우에서 런타임 에러가 발생했다.

코드를 작성하면서 고민한 점이 before와 after의 같은 자리를 비교했을 때 같은지 확인하면 되겠다 생각했다.

그때 생각난게 리스트에 아스키코드로 변환해서 집어넣고, 정렬한 뒤 리스트가 같은지 확인하는 것이었다.

def solution(before, after):
    before_list = []
    after_list = []
    for i in before:
        before_list.append(ord(i))
    for i in after:
        after_list.append(ord(i))
    before_list.sort()
    after_list.sort()
    if before_list == after_list:
        return 1
    else:
        return 0

 결과는 통과였고 지금 작성된 코드를 살펴보다 분명 알파벳만 있어도 sort()로 정렬할 수 있던 것으로 알고 있었다.

 

 해결 방법

def solution(before, after):
    before_list = []
    after_list = []
    for i in before:
        before_list.append(i)
    for i in after:
        after_list.append(i)
    before_list.sort()
    after_list.sort()
    if before_list == after_list:
        return 1
    else:
        return 0

역시나 ord()를 지워도 알파벳이 sort()되면서 결과가 올바르게 출력된다.

def solution(before, after):
    # dictionary로 만들어서 value의 숫자를 세고 일치하면 1, 아니면 0
    after_dict = {}
    before_dict = {}
    count = 0
    for i in before:
        if i not in before_dict:
            before_dict[i] = 1
        elif i in before_dict:
            before_dict[i] += 1

    for i in after:
        if i not in after_dict:
            after_dict[i] = 1
        elif i in after_dict:
            after_dict[i] += 1
            
    for i in after_dict.items():
        for n in before_dict.items():
            if i == n:
                count += 1
    # 일치하는 알파벳 종류와 총 알파벳의 종류가 같으면 1
    if count == len(after_dict):
        return 1
    else:
        return 0

처음에 만들고 실패한 dictionary를 활용한 코드를 수정해 봤는데 위의 조건이 더 깔끔해 보이는데 이건 통과했다.

if before_dict[i] != after_dict[i]:

첫 번째 코드에서 런타임 에러가 발생한 이유는 after에서만 들어간 알파벳이 if문에서 before_dict에 들어가면서 발생한 것이었다.

def solution(before, after):
    # dictionary로 만들어서 value의 숫자를 세고 일치하면 1, 아니면 0
    after_dict = {}
    before_dict = {}
    for i in before:
        if i not in before_dict:
            before_dict[i] = 1
        elif i in before_dict:
            before_dict[i] += 1

    for i in after:
        if i not in after_dict:
            after_dict[i] = 1
        elif i in after_dict:
            after_dict[i] += 1

    for i in after_dict.keys():
        if before_dict.get(i) != after_dict.get(i):
            return 0
    return 1

 알게 된 점

str로 이루어진 리스트도 sort()를 적용할 수 있다.

 에러 가능성을 최소화하기 위해서 get과 같이 값이 없을 때는 None을 return 하는 함수를 애용하자

백준 알고리즘 문제를 풀면서 알게 된 점

import sys
b, c = map(int, sys.stdin.readline().split()) # map을 사용하면 여러 요소를 한 번에 형변환 가능
print(sys.stdin.readline())  # 3 입력시 3 + \n으로 개행 포함, 반복 사용시 end 넣고 사용
.rjust(기준 숫자, 공백의 텍스트)

# 끝까지 읽어들이기를 try:, except:로 사용가능

'개발일지 > TIL' 카테고리의 다른 글

TIL 23-04-11  (0) 2023.04.11
TIL 23-04-10  (0) 2023.04.10
TIL 23-04-08  (0) 2023.04.08
TIL 23-04-07  (2) 2023.04.07
TIL 23-04-06  (0) 2023.04.06