첫번째 코드
리스트를 만들어서 체육복이 있으면 1, 없으면 0으로 해서 모두 더한 값이 수업을 들을 수 있는 학생수이다!라는 아이디어
def solution(n, lost, reserve):
clothes = [1] * (n+2)
for i in lost:
clothes[i] = 0
for i in reserve:
if clothes[i] == 0:
clothes[i] = 1
elif clothes[i-1] == 0:
clothes[i-1] = 1
elif clothes[i+1] == 0:
clothes[i+1] = 1
return sum(clothes) - 2
오류;
두번째 코드
이유를 찾았다!
자신의 체육복이 도난 당한 경우에 자신의 체육복을 입어야 한다.
예를 들어,
lost = [2, 4, 5]
reseve = [2, 3, 4]
인 경우에 2와 4는 자신의 체육복을 입는다.
하지만 내가 작성한 코드는 2가 2에게, 3이 4에게, 4가 5에게 체육복을 준다;
문제를 해결하기 위해 lost와 reserve에 동일한 값이 있는 경우에 해당 값을 제거하고 진행하도록 한다.
def solution(n, lost, reserve):
clothes = [1] * (n+2)
for i in lost:
for j in reserve:
if i == j:
del lost[lost.index(i)]
del reserve[reserve.index(j)]
for i in lost:
clothes[i] = 0
while reserve:
i = reserve.pop(0)
if clothes[i] == 0:
clothes[i] = 1
elif clothes[i-1] == 0:
clothes[i-1] = 1
elif clothes[i+1] == 0:
clothes[i+1] = 1
return sum(clothes) - 2
오류;
lost를 매개변수로 가져오는 조건문에서 lost를 건들였더니 문제가 생겼다.
세번째 코드
lost를 건들이지 않고 lost안의 모든 값을 for문에 사용하는 방법은 lost[:]를 사용하는 것이다.
lost[:]를 사용하면 lost를 복사하여 사용한다고 생각하면 된다.
즉, 조건문에서 lost를 수정해도 원래 lost값에서 i를 가져와서 사용할 수 있다!
def solution(n, lost, reserve):
clothes = [1] * (n+2)
for i in lost[:]:
if i in reserve:
reserve.remove(i)
lost.remove(i)
for i in lost:
clothes[i] = 0
while reserve:
i = reserve.pop(0)
if clothes[i] == 0:
clothes[i] = 1
elif clothes[i-1] == 0:
clothes[i-1] = 1
elif clothes[i+1] == 0:
clothes[i+1] = 1
return sum(clothes) - 2
오류...? 왜징?
네번째 코드
lost과 reserve가 순서대로 있을 것이라는 내용이 없다!
그렇기 때문에 순서가 거꾸로 있는 경우 문제가 된다.
lost = [5, 3]
reserve = [4, 2]인 경우
내 코드에서는 4가 3에게 줘버린다...
그렇기 때문에 앞에서부터 숫자를 고려하는 조건문이므로 sort를 통해 모두 오름차순으로 정렬하도록 한다.
def solution(n, lost, reserve):
clothes = [1] * (n+2)
for i in lost[:]:
if i in reserve:
reserve.remove(i)
lost.remove(i)
for i in lost:
clothes[i] = 0
lost.sort()
reserve.sort()
while reserve:
i = reserve.pop(0)
if clothes[i] == 0:
clothes[i] = 1
elif clothes[i-1] == 0:
clothes[i-1] = 1
elif clothes[i+1] == 0:
clothes[i+1] = 1
return sum(clothes) - 2
통과:)
후 고생 많았다!
링크
'코딩 테스트 > 프로그래머스' 카테고리의 다른 글
최대공약수와 최소공배수 (0) | 2024.04.30 |
---|---|
푸드 파이트 대회 (2) | 2024.04.26 |
가장 가까운 같은 글자 (2) | 2024.04.25 |
정수 내림차순으로 배치하기 (2) | 2024.04.21 |
나머지가 1이 되는 수 찾기 (0) | 2024.04.20 |