[프로그래머스_스택/큐_Lv2] 프린터

Lee, Chankyu·2022년 1월 9일
0
post-thumbnail

프린터

문제 링크

나의 풀이

🙅‍♂️ 잘못된 풀이

def solution(priorities, location):
    complete = []
    myLocation = priorities[location]

    while len(priorities) > 0:
        if priorities[0] == max(priorities):
            complete.append(priorities.pop(0))

        else:
            priorities.append(priorities.pop(0))

    return complete.index(myLocation) + 1 
  • 두 번째 입출력 예 에서 통과할 수 없는 로직이다. 중요도가 같은 문서가 있을 경우 구분 할 수 없어서 오답이었다.
  • enumerate를 사용해서 인덱스 값을 고유 값으로 사용할 생각을 못했다...

🙆‍♂️ 정답 풀이(deque 이용)

from collections import deque


def solution(priorities, location):
    answer = 0
    a = deque([(j, i) for i,j in enumerate(priorities)])

    while len(a):
        list = a.popleft()
        if a and max(a)[0] > list[0]: # if max(a)[0] > list[0]: 으로 하면 런타임에러가 뜬다... 
            a.append(list)
        else:
            answer += 1
            if list[1] == location:
                break
    return answer
  • 지난번 공부했었던 collections 모듈의 deque를 사용하였고 enumerate를 통해 인덱스 값으로 문서의 중요도가 같은 경우를 구분할 수 있었다.

  • 처음에는 if max(a)[0] > list[0]:(위의 코드에서 주석을 단 줄) 으로 코드를 작성하였는데 테스트를 돌려보니 런타임 에러가 났다. 아직 if a and~ 로 해야하는 이유를 완전히 이해는 못하였다. 완벽히 알아내서 업데이트 하도록 하겠다.


다른 사람의 풀이

def solution(priorities, location):
    answer = 0

    array1 = [c for c in range(len(priorities))] # index 위치 저장 
    array2 = priorities.copy() # 값 저장 (출력되는 값)

    i = 0
    while True:
        if array2[i] < max(array2[i+1:]):
            array1.append(array1.pop(i))
            array2.append(array2.pop(i))
        else:
            i += 1

        if array2 == sorted(array2, reverse=True):
            break

    return array1.index(location) + 1
  • 하단 부분에 sorted() 내림차순을 이용하여 문서들의 출력순서를 결정하는 것이 인상적이었다. 내림차순 했을때의 정렬과 똑같을때 인덱스 값을 저장해둔 배열에서의 인덱스 값을 찾으면 되는 것이다.

def solution(priorities, location):
    queue =  [(i,p) for i,p in enumerate(priorities)]
    answer = 0
    while True:
        cur = queue.pop(0)
        if any(cur[1] < q[1] for q in queue):
            queue.append(cur)
        else:
            answer += 1
            if cur[0] == location:
                return answer
  • any 를 쓰는 코드를 처음 봐서 가져와봤다.

📝 any()와 all()은 iterable한 객체를 받는데 이 객체를 돌면서 조건을 검사해 답을 True/False의 답을 반환한다.

  • any() : 하나라도 True인게 있으면 True
  • all() : 모두 True여야 True 반환
profile
Backend Developer - "Growth itself contains the germ of happiness"

0개의 댓글