algorithm/python

프로그래머스/스택,큐/프린터

아르르르를를르 2022. 6. 20. 18:02

https://programmers.co.kr/learn/courses/30/lessons/42587?language=python3 

 

- 1차 풀이 (flag 사용)

from collections import deque

def solution(priorities, location):
    answer = []
    stack = deque([i for i in range(0, len(priorities))])
    priorities = deque(priorities)
    
    while priorities:
        flag = 0
        for priority in priorities:
            if priority > priorities[0]:
                flag = 1
                break
        else:
            priorities.popleft()
            answer.append(stack.popleft())

        if flag:
            item = priorities.popleft()
            priorities.append(item)
            item = stack.popleft()
            stack.append(item) 

    return answer.index(location) + 1

 

 

- 2차 풀이 (훨씬 간결하고 효율적인 로직)

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