코딩테스트 연습 - 프린터
우선순위가 있는 프린터를 개발했다. 내가 인쇄 요청한 문서가 몇 번째로 인쇄되는지 구하라.
우선순위 리스트를 queue로 만들고 앞에서부터 뽑았다. 해당 문서보다 중요도가 높은 문서가 있을 경우 뒤로 보내고, 없을 경우 뽑는다. 뽑은 문서가 내가 인쇄 요청한 문서가 나올 때까지 출력한다.
from collections import deque
def solution(priorities, location):
answer = 0
priorities = deque(priorities)
while priorities:
left = priorities.popleft()
if [i for i in priorities if left < i]: # 첫번째 문서보다 중요도 높은 문서가 있는 경우
location -= 1
priorities.append(left)
if location < 0:
location = len(priorities) - 1
continue
else: # 중요도가 가장 높은 문서일 경우
if location == 0: # 원하는 문서일 경우
answer += 1
break
else: # 원하지 않는 문서일 경우
answer += 1
location -= 1
return answer
any()는 조건문 for ~ in ~ 을 만족하는 값이 하나라도 존재하면 True를 반환하는 함수인 것 같다. 알아두자!
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