[알고리즘] 프로그래머스

hoya.a·2022년 6월 18일
0

알고리즘

목록 보기
10/10
post-thumbnail

Q1. 2016년
레벨 1

def solution(a, b):
    temp = 0
    dayofweek = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    days = ["FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"]

    for i in range(1, a):
        temp += dayofweek[i]

    temp += b - 1
    temp = temp % 7

    return days[temp]

Q2. 신고 결과 받기
레벨 1

from collections import defaultdict


def solution(id_list, report, k):
    answer = [0] * len(id_list)
    
    # 주어지는 report 리스트를 중복 제거 해주는 것이 이 문제의 핵심이었다.
    # 이 한줄의 코드 없이 제출하면 수많은 시간초과를 만날 수 있다.
    report = set(report)
    
    user_list_who_i_report = defaultdict(set)
    num_of_reported = defaultdict(int)
    suspended = []

    for r in report:
        do_report, be_reported = r.split()
        
        num_of_reported[be_reported] += 1
        user_list_who_i_report[do_report].add(be_reported)
        
        if num_of_reported[be_reported] == k:
            suspended.append(be_reported)

    for s in suspended:
        for i in range(len(id_list)):
            if s in user_list_who_i_report[id_list[i]]:
                answer[i] += 1

    return answer

답 출처

1번은 리스트에 한달에 몇일씩 있는지와 각 요일을 담아서 초기값0인 변수에 더해주는 생각까지는 했지만 그 뒤로 어떻게 해야할지 몰라서 정답을 보았고
2번은 딕셔너리 형태로 각 유저가 신고한 유저 목록과 신고당한 유저를 만들어서 answer를 [0, 0, 0, 0] 으로 초기화해서 정지된 유저를 신고한 유저의 값을 1씩 증가시키려고 했지만 어려워 답을 보니 defaultdict를 사용하여 푸는 방법에 대해 알게 되었다..

몰랐던 파이썬 문법

1. set(집합)

  • set은 수학에서 이야기하는 집합과 비슷하다.

  • 순서가 없어 어떤 값이 먼저 나올지 알 수 없다.

  • 딕셔너리와 비슷하지만 key가 없고 vaule만 존재

  • 증복된 값은 자동으로 중복이 제거 된다.

    ex)
    s = {3, 4, 5}

    ex2)
    s = {1, 1, 2, 2, 3, 4}
    -> s
    {1, 2, 3, 4}

2. if ~ in 과 if ~ not in

  • if A in B : B안에 A가 있으면 참이다.
  • if A not in B : B안에 A가 없으면 참이다.
  • B에는 리스트 , 튜플, 문자열을 사용할 수 있다.
profile
TIL 정리

0개의 댓글