[프그] > 스택/큐 > 프린터 ★

yozzum·2022년 4월 3일
0

내가짠코드

  • 흐름대로 따라가긴 했으나, index를 함께 별도로 저장해놓고 처리할 생각을 못했다. 왜 못했을까...
def solution(priorities, location):
    mx = max(priorities)
    cnt = 1
    while True:
        if priorities[0] < mx:
            temp = priorities.pop(0)
            priorities.append(temp)
            location -= 1
            #print("P", priorities, "L", location)
        elif priorities[0] == mx:
            if location == 0 or len(priorities) == abs(location):
                #print("P", priorities, "L", location)
                break
            priorities.pop(0)
            priorities.append(0)
            location -=1
            cnt += 1
            mx = max(priorities)
            #print("P", priorities, "L", location)
            
    #print(cnt)
    return cnt

잘짠코드

  • 기존 리스트(priorities)와 내림차순으로 정렬된 리스트(search)를 따로 가져갑니다.
  • 기존 리스트의 index도 함께 봅니다.
  • search에서는 cursor 변수를 생성
def solution(priorities, location):
    answer = 0
    search, cursor = sorted(priorities, reverse=True), 0
    
    while True:
        for idx, priority in enumerate(priorities):
            s = search[cursor] # max value
            if priority == s: # if the priority value equals max value
                cursor += 1 # move current cursor to the right
                answer += 1 # print the max
                if idx == location:
                    break
        else:
            continue
        break
    return answer

풀이 이해를 위한 출력

idx 0 priority 1 cursor 0 s 9 answer 0
idx 1 priority 1 cursor 0 s 9 answer 0
idx 2 priority 9 cursor 0 s 9 answer 0
idx 3 priority 1 cursor 1 s 1 answer 1
idx 4 priority 1 cursor 2 s 1 answer 2
idx 5 priority 1 cursor 3 s 1 answer 3
idx 0 priority 1 cursor 4 s 1 answer 4
직후에 cursor, answer += 1 하고 break
답 : 5

좋아요 제일 많이 받은 코드

from collections import deque

def solution(priorities, location):
    queue =  deque([(i,p) for i,p in enumerate(priorities)])
    answer = 0
    while True:
        cur = queue.popleft()
        if any(cur[1] < q[1] for q in queue):
            queue.append(cur)
        else:
            answer += 1
            if cur[0] == location:
                return answer

풀이

  • 이 코드가 가장 직관적으로 이해가 된다.
  • python 의 any 함수를 적절히 사용했다.
  • 같은 값이 있더라도 location을 정확하게 처리하기 위해서 index도 함께 튜플형태로 queue에 넣어놓고 처리하는 것이 포인트이다.
  • 현재 커서가 가리키는 튜플을 일단 queue에서 빼내고, 이보다 큰값이 존재하면 뒤에다가 어펜드하는 것이다.
  • 만약 이보다 큰 값이 존재하지 않으면 max 값인 것이니까 append하지 않고 출력(answer+=1)한다.
  • 출력하고나서 index와 location을 비교해서 정답을 return 한다.
profile
yozzum

0개의 댓글