본문 바로가기
Algorithm

[프로그래머스] 체육복 (python)

by YGSEO 2021. 1. 18.
728x90

Python

주의사항은 여벌을 가지고 있는 리스트에서도 도난이 발생할 수 있기 때문에

lost와 reserve 각각에 대해서 중복이 없게 차집합을 만들어 놓아야 한다. (first two lines of codes.)

 

그리고 여벌 리스트(rsv_pos)를 loop돌면서 도난 당한 리스트(lost_pos)의 앞 or 뒤에 여벌리스트의 요소들이 있는지 체크하면서 도난 리스트를 제거한다.

 

python remove method는 list에서 remove에 주어진 item을 찾아서 삭제하는 메서드이다. 만약, 해당 아이템이 없다면

"ValueError: list.remove(x): x not in list" 이러한 에러 메시지를 보게될 것이다.

def solution(n, lost, reserve):
    rsv_pos = set(reserve) - set(lost)
    lost_pos = set(lost) - set(reserve)
    
    for a in rsv_pos:
        if a - 1 in lost_pos:
            lost_pos.remove(a-1)
        elif a + 1 in lost_pos:
            lost_pos.remove(a+1)
        
    answer = n - len(lost_pos)
    return answer

만약에 왼쪽부터 확인하지 않고 오른쪽부터(a+1) 확인을하면서 제거한다면 틀리는 경우가 발생한다.

정렬된 집합을 loop하면서 확인하기 때문에 오른쪽부터 확인을 한다면

rain-bow.tistory.com/entry/Python-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%B2%B4%EC%9C%A1%EB%B3%B5

위 그림에서 2, 4 번 학생은 도난을 당한 상황인데 오른쪽부터 탐색을 한다면 2번이 충분이 여벌의 체육복을 받을 수 있는 상황임에도 받지 못하는 경우가 발생한다. (3번이 여벌을 4번에게 주기 때문에)

 

*set 자료형은 순서가 없는(unordered) 자료형이기 때문에 reversed도 작동하지 않는다.

 

왼쪽부터 해야하는 이유:

in-bow.tistory.com/entry/Python-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%B2%B4%EC%9C%A1%EB%B3%B5


def solution(n, lost, reserve):
    inter = set(lost) & set(reserve)
    l = set(lost) - inter
    r = set(reserve) - inter
    
    for x in r:
        if x-1 in l:
            l.remove(x-1)
        elif x+1 in l:
            l.remove(x+1)
    
    return n - len(l)
728x90

댓글