프로그래머스/Lv.1
2022 KAKAO BLIND RECRUITMENT > 신고 결과 받기 - Python, defaultdict, set, defaultdict 없이 초기화하기
아찌방
2024. 11. 16. 00:12
https://school.programmers.co.kr/learn/courses/30/lessons/92334
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
풀이 - 나의 생각
한 유저가 여러명을 신고 할 수 있지만
중복으로 신고는 못합니다.
그래서 신고자별 신고 대상자를 set으로 중복 제거하면서 dict로 저장합니다.
그 dict를 이용해서 신고 횟수를 세고
그 신고 횟수가 k개 이상이면
카운트를 세주면 됩니다.
user_list를 참고하여
dict에 유저명과 위치를 기록합니다.
#defaultdict not use
userIndex = {user:idx for idx, user for enumerate(user_list)}
그 후 report를 set으로 중복제거 후
신고 당한 횟수를 카운트 해줍니다.
마지막으로
중복 제거된 report를 돌면서
신고 당한 횟수가 k 이상이면
신고자의 위치에 +1 을 해줍니다.
코드
from collections import defaultdict
def solution(id_list, report, k):
# 유저별 신고 대상 기록
declarationList = defaultdict(set)
for declaration in set(report):
section = declaration.split(" ")
declarationList[section[0]].add(section[1])
# 2번 이상 신고된 유저 파악
block = defaultdict(int)
for history in declarationList:
for user in declarationList[history]:
block[user]+=1
# 유저별 신고 대상자 비교해서 카운트 후 반환
return [sum(1 for x in declarationList[user] if block[x] >= k) for user in id_list]
from collections import defaultdict
def solution(id_list, report, k):
declarationList = defaultdict(set)
block = defaultdict(int)
# 유저별 신고 대상 기록
for declaration in set(report):
section = declaration.split(" ")
if section[1] not in declarationList[section[0]]: # 2번 이상 신고된 유저 파악
declarationList[section[0]].add(section[1])
block[section[1]]+=1
# 유저별 신고 대상자 비교해서 카운트 후 반환
return [sum(1 for x in declarationList[user] if block[x] >= k) for user in id_list]
def solution(user_list, report, k):
# 결과 배열과 유저 이름 -> 인덱스 매핑
answer = [0] * len(user_list)
user_to_index = {user: idx for idx, user in enumerate(user_list)}
# 신고 횟수 기록
report_count = {user: 0 for user in user_list}
for entry in set(report):
report_count[entry.split()[1]] += 1
# 결과 계산
for entry in set(report):
reporter, reported_user = entry.split()
if report_count[reported_user] >= k:
answer[user_to_index[reporter]] += 1
return answer
# report = set(report)
# 이렇게 해서 for 문에 report로 해도 되는데
# 속도가 좀 더 빨라지긴 하는데, 메모리 사용량은 조금 올라갑니다.
728x90