✅ 코드
1. 런타임 에러
def solution(answers):
dict = {1:0, 2:0, 3:0}
lst = [[1,2,3,4,5,1,2,3,4,5], [2,1,2,3,2,4,2,5,2,1], [3,3,1,1,2,2,4,4,5,5]]
for i in range(len(answers)):
for j in range(len(lst)):
if answers[i] == lst[j][i]:
dict[j+1] += 1
for i in range(1,4):
if dict[i] == 0:
del dict[i]
return sorted(dict)
2. 개선 답안
def solution(answers):
dict = {1:0, 2:0, 3:0}
lst = [[1,2,3,4,5], [2,1,2,3,2,4,2,5], [3,3,1,1,2,2,4,4,5,5]]
for id, answer in enumerate(answers):
for lst_id, lst_answer in enumerate(lst, start=1):
if answer == lst_answer[id % len(lst_answer)]:
dict[lst_id] += 1
return [i for i in dict if dict[i] == max(dict.values())]
☑️ 핵심 코드
1. enumerate(iterable, start=0)
for i in enumerate(['a', 'b', 'c']):
print(i)
> (0, 'a')
> (1, 'b')
> (2, 'c')
for j, i in enumerate(['a', 'b', 'c']):
print(j, i)
> 0 a
> 1 b
> 2 c
2. %(나머지)
0 % 5
> 0
6 % 5
> 1
3. return 문에 list comprehension 사용