[Python] 프로그래머스 - Level1 - 신고 결과 받기

강주형·2022년 8월 7일
0

2022 KAKAO BLIND RECRUITMENT

https://school.programmers.co.kr/learn/courses/30/lessons/92334

프로그래머스 처음 풀어봤는데, 레벨1도 만만치 않다..

감이 안 잡혀서 처음에는 실행 시간을 고려하지 않고 완성을 목적으로 코드를 짰음

# 7개 시간 초과

from collections import Counter

def solution(id_list, report, k):    
    report_unique = Counter(report).most_common()

    count = [0 for i in range(len(id_list))]
    answer = [0 for i in range(len(id_list))]
    suspen_list = []

    for i in range(len(report_unique)):
        for idx, val in enumerate(id_list):
            if val == report_unique[i][0].split()[1]:
                count[idx] += 1
    for idx, val in enumerate(count):
        if val >= k:
            suspen_list.append(id_list[idx])
    print(suspen_list)

    for sus in suspen_list:
        for i in range(len(report_unique)):
            if sus == report_unique[i][0].split()[1]:
                for idx, val in enumerate(id_list):
                    if val == report_unique[i][0].split()[0]:
                        answer[idx] += 1
    return answer

7개 케이스에서 시간 초과 발생

most_common() 사용하지 않고, defaultdict를 사용해서 풀이해보기로 결정

defaultdict는 딕셔너리와 비슷한데, key에 대한 value를 따로 지정하지 않아도, 자동으로 0으로 설정이 가능

아래 예시

from collections import defaultdict
dd = defaultdict(int) # int를 기본으로 설정
dd['test1'] = 1
dd['test2']
print(dd)
print(dd['test1'])
print(dd['test2'])
print(dd['test3'])
defaultdict(<class 'int'>, {'test1': 1, 'test2': 0})
1
0
0

이걸 사용하고, unique 값을 뽑는 건 set을 이용하기로 결정

# 2개 시간 초과

from collections import defaultdict

def solution(id_list, report, k):    
    report_count = defaultdict(int)
    reported_count = defaultdict(int)
    suspension = []
    answer = []
    report_uniq = list(set(report))
    
    for i in range(len(report_uniq)):
        reported_count[report_uniq[i].split()[1]] += 1

    for i in reported_count:
        if reported_count[i] >= k:
            suspension.append(i)

    for i in range(len(report_uniq)):
        for sus in suspension:
            if report_uniq[i].split()[1] == sus:
                report_count[report_uniq[i].split()[0]] += 1

    for id in id_list:
        answer.append(report_count[id])
    return answer

2개 케이스에서 시간 초과 발생

아무래도 2중 for문이 문제인 것 같아서 저걸 줄여보기로 함
suspension의 원소를 굳이 저렇게 반복문으로 탐색할 필요가 없었음

아래처럼 수정

# 성공

from collections import defaultdict

def solution(id_list, report, k):    
    report_count = defaultdict(int)
    reported_count = defaultdict(int)
    suspension = []
    answer = []
    report_uniq = list(set(report))
    
    for i in range(len(report_uniq)):
        reported_count[report_uniq[i].split()[1]] += 1

    for i in reported_count:
        if reported_count[i] >= k:
            suspension.append(i)

    for i in range(len(report_uniq)):
        if report_uniq[i].split()[1] in suspension:
            report_count[report_uniq[i].split()[0]] += 1

    for id in id_list:
        answer.append(report_count[id])
    return answer

if문으로 바로 탐색이 가능함

레벨1이 이렇게 어렵다니..

풀고 다른 사람들 코드를 확인해보니 별도의 라이브러리도 불러오지 않고, 15줄 미만의 코드도 있었음...

참고하면서 연습해보자

profile
Statistics & Data Science

0개의 댓글