수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다.
1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...
1번 문제부터 마지막 문제까지의 정답이 순서대로 들은 배열 answers가 주어졌을 때, 가장 많은 문제를 맞힌 사람이 누구인지 배열에 담아 return 하도록 solution 함수를 작성해주세요.
enumerate(iterable, start=0)
- iterable은 시퀀스, 이터레이터 또는 이터레이션을 지원하는 다른 객체여야 합니다.
- 인덱스와 원소에 동시 접근할 수 있습니다.
- 참고자료: https://docs.python.org/ko/3/library/functions.html
code - 1차
def solution(answers):
result = []
sol1 = [1, 2, 3, 4, 5] * len(answers)
sol2 = [2, 1, 2, 3, 2, 4, 2, 5] * len(answers)
sol3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] * len(answers)
count1, count2, count3 = 0, 0, 0
# 1번~3번 수포자 문제 정답여부 확인
for i in range(len(answers)):
if sol1[i] == answers[i]:
count1 += 1
for i in range(len(answers)):
if sol2[i] == answers[i]:
count2 += 1
for i in range(len(answers)):
if sol3[i] == answers[i]:
count3 += 1
# 가장 높은 점수 받은 사람(return값 오름차순)
if count1 == count2 == count3:
result.append(1)
result.append(2)
result.append(3)
elif count1 == count2 and count1 > count3:
result.append(1)
result.append(2)
elif count1 == count3 and count1 > count2:
result.append(1)
result.append(3)
elif count1 > count2 and count1 > count3:
result.append(1)
elif count2 == count3 and count2 > count1:
result.append(2)
result.append(3)
elif count2 > count3 and count2 > count1:
result.append(2)
else:
result.append(3)
return result
code - 2차
def solution(answers):
p1 = [1, 2, 3, 4, 5]
p2 = [2, 1, 2, 3, 2, 4, 2, 5]
p3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
count = [0, 0, 0]
result = []
for idx, answer in enumerate(answers):
if answer == p1[idx%len(p1)]:
count[0] += 1
if answer == p2[idx%len(p2)]:
count[1] += 1
if answer == p3[idx%len(p3)]:
count[2] += 1
for idx, answer in enumerate(count):
if count[idx] == max(count):
result.append(idx+1)
return result
- enumerate 함수를 사용하여 인덱스와 원소에 직접 접근하는 방식으로 리팩토링하였습니다.
https://github.com/seonmin5/codingtest_Python
GitHub - seonmin5/codingtest_Python
Contribute to seonmin5/codingtest_Python development by creating an account on GitHub.
github.com
반응형
'Python' 카테고리의 다른 글
[Python/level 0] 문자열 정렬하기 (2) - 120911, sorted (0) | 2024.08.31 |
---|---|
[Python/level 0] 369게임 - 120891, str, count (0) | 2024.08.30 |
[Python/level 0] 인덱스 바꾸기 - 120895, 리스트 (0) | 2024.08.30 |
[Python/level 0] 문자열의 뒤의 n글자 - 181910, len, 리스트 슬라이싱 (0) | 2024.08.30 |
[Python/level 0] 배열의 유사도 - 120903, len, 리스트 컴프리헨션 (0) | 2024.08.30 |