프로그래머스 > 추억점수

weonyee·2026년 1월 8일

codingtest

목록 보기
4/7

추억점수 - 문제로 바로 가기

내 답안

def solution(name, yearning, photo):
    namelst = set(name)
    cnt = {}
    for i in range(len(name)):
        cnt[name[i]] = yearning[i]
        
    ans = []
    for item in photo:
        score = 0
        for p in item:
            if p in namelst:
                score += cnt[p]
            else: pass
        ans.append(score)
    return ans
  1. 이름 - yearning을 연결하는 딕셔너리를 생성
  2. 점수계산
    2-1. 이름 리스트에 있는지 확인
    2-2. 없다면 -> 패스
    2-3. 있다면 점수를 더함
  3. 결과 출력

입력값의 크기가 작기 때문에 문제는 통과했지만, 이름 - yearning 딕셔너리를 생성하는 것이 비효율적인 것 같았음.

+) if p in namelst: 가 없었더니 딕셔너리에 없는 이름에 대한 valueerror 발생

GPT 코드

def solution(name, yearning, photo):
    score_map = dict(zip(name, yearning))
    return [sum(score_map.get(p, 0) for p in item) for item in photo]

1. name - yearning 딕셔너리 생성

cnt = {}
    for i in range(len(name)):
        cnt[name[i]] = yearning[i]

를 다음과 같이 표현.

score_map = dict(zip(name, yearning))

zip 👉 같은 인덱스끼리 묶어서 튜플로 만들어줌

2. 이름이 존재하면 해당되는 yearning을 결과에 더함

ans = []
    for item in photo:
        score = 0
        for p in item:
            if p in namelst:
                score += cnt[p]
            else: pass
        ans.append(score)

를 다음과 같이 표현.

return [sum(score_map.get(p, 0) for p in item) for item in photo]

dict.get(key, default) -> key값이 없으면 default 값으로 처리됨

  • python의 강점을 가장 잘 살린 것 -> (expression, generator)

0개의 댓글