문제주소 : https://programmers.co.kr/learn/courses/30/lessons/42840
문제와 답을 1대 1로 대응해 일치한 개수를 count하는 문제이므로 완전탐색을 이용해 해결한다.
문제는 최대 10000개 이므로 1번, 2번, 3번의 list길이를 10000개까지 미리 늘리고
answers의 길이만큼 반복하여 1대 1로 대응하여 일치한 개수를 count한다.
def solution(answers):
# 1번, 2번, 3번의 패턴을 10000개까지 미리 늘려놓는다.
no1 = [1, 2, 3, 4, 5] * (10000 // 5)
no2 = [2, 1, 2, 3, 2, 4, 2, 5] * (10000 // 8)
no3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] * (10000 // 10)
# 순서대로 비교하여 answers와 일치한 값을 count해 저장할 변수
no1_cnt = 0
no2_cnt = 0
no3_cnt = 0
# answers의 길이만큼 비교를 반복 -> 일치하면 count 추가
for i in range(len(answers)):
if no1[i] == answers[i]:
no1_cnt += 1
if no2[i] == answers[i]:
no2_cnt += 1
if no3[i] == answers[i]:
no3_cnt += 1
# count의 값을 비교하여 return
if no1_cnt == no2_cnt and no1_cnt == no3_cnt:
return [1, 2, 3]
elif no1_cnt == no2_cnt and no1_cnt > no3_cnt:
return [1, 2]
elif no1_cnt == no3_cnt and no1_cnt > no2_cnt:
return [1, 3]
elif no2_cnt == no3_cnt and no2_cnt > no1_cnt:
return [2, 3]
elif no1_cnt > no2_cnt and no1_cnt > no3_cnt:
return [1]
elif no2_cnt > no1_cnt and no2_cnt > no3_cnt:
return [2]
elif no3_cnt > no1_cnt and no3_cnt > no2_cnt:
return [3]
count를 리턴하는 방법이 너무 일차원적이라 다른 방법을 고민해보았으나 생각나는 방법이 없었다.
답안을 제출 후 다른 사람의 코드에서 list의 max()를 이용하여 해결한 방법이 깔끔해보였다.
def solution(answers):
# 1번, 2번, 3번의 패턴을 10000개까지 미리 늘려놓는다.
no1 = [1, 2, 3, 4, 5] * (10000 // 5)
no2 = [2, 1, 2, 3, 2, 4, 2, 5] * (10000 // 8)
no3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] * (10000 // 10)
# 순서대로 비교하여 answers와 일치한 값을 count해 저장할 변수
no1_cnt = 0
no2_cnt = 0
no3_cnt = 0
# answers의 길이만큼 비교를 반복 -> 일치하면 count 추가
for i in range(len(answers)):
if no1[i] == answers[i]:
no1_cnt += 1
if no2[i] == answers[i]:
no2_cnt += 1
if no3[i] == answers[i]:
no3_cnt += 1
# max()를 사용하기 위해 count를 list에 담고 결과를 return할 answer를 생성
count = [no1_cnt, no2_cnt, no3_cnt]
answer = []
# max()를 이용해 결과를 return
if count[0] == max(count):
answer.append(1)
if count[1] == max(count):
answer.append(2)
if count[2] == max(count):
answer.append(3)
return answer
'알고리즘 공부 > 플레이데이터 알고리즘 스터디' 카테고리의 다른 글
210531 완전/이진탐색 - 숫자카드2 (0) | 2021.05.31 |
---|---|
210530 완전/이진탐색 - 소수찾기 (0) | 2021.05.30 |
210523 스택/큐 - 다리를 지나는 트럭 문제 (0) | 2021.05.23 |
210523 스택/큐 - 기능개발 문제 (0) | 2021.05.23 |
210523 스택/큐 - 주식가격 문제 (0) | 2021.05.23 |