우당탕탕 개발일지
[스택/큐] 프로그래머스 level 2 프로세스 (Python 파이썬) 본문
💡문제 링크
💡문제 분석 요약
여러 프로세스들이 우선순위에 따라서 실행된다.
1. 실행 대기 큐에서 원소를 하나 꺼낸다.
2. 큐에 대기 중인 프로세스 중 우선순위가 더 높은 프로세스가 있으면 꺼낸 프로세스를 다시 큐에 넣는다.
3. 큐에 대기 중인 프로세스 중 우선순위가 더 높은 프로세스가 없으면 꺼낸 프로세스를 실행한다.
4. 한 번 실행한 프로세스는 다시 큐에 넣지 않는다.
location은 프로세스의 위치를 알려주는 정수이고, priorities는 프로세스의 우선순위가 담긴 배열이다.
location에 해당하는 프로세스의 우선순위는 priorities[location]이다.
priorities와 location이 매개변수로 주어질 때, 해당 프로세스가 몇 번째로 시행되는지를 출
💡알고리즘 설계
실행되는 프로세스의 location 정보가 담을 배열 execute을 생성한다.(빈 배열)
0부터 priorities의 길이 - 1까지를 원소로 갖는 큐 num을 만든다.
priorities를 큐 자료구조로 만든다.
priorities가 텅 빈 큐가 될 때까지 아래의 과정을 무한반복한다.
1. priorities에서 프로세스 하나, num에서 숫자 하나를 빼낸다.
2. priorities에서 프로세스 하나 빼고 나니 텅 비었다면, 그 빼낸 프로세스에 대응하는 숫자(location)을 execute 배열에 더한다.
3. priorities 원소의 최댓값이 p보다 크다면 p를 다시 큐에 넣고 n도 다시 큐에 넣는다.
4. 그렇지 않다면 n을 execute 리스트에 append한다.
5. execute[location] + 1을 반환한다.
💡코드
from collections import deque
def solution(priorities, location):
execute = []
num = deque(list(range(len(priorities))))
priorities = deque(priorities)
# priorities가 텅 빈 큐가 될 때까지 무한반복
while len(priorities) > 0:
# priorities에서 맨 앞 원소를 꺼내서 p 변수에 넣고, num에서 맨 앞 원소를 꺼내서 n 변수에 넣기
p = priorities.popleft()
n = num.popleft()
# priorities 원소의 최댓값이 p보다 크다면 p를 다시 큐에 넣고 n도 다시 큐에 넣기
if priorities == deque():
execute.append(n)
print(f"우선순위가 {p}인 프로세스 {n}를 실행한다.")
break
if max(priorities) > p:
priorities.append(p)
num.append(n)
print(f"우선순위가 {p}인 프로세스 {n}를 다시 큐에 넣는다.")
# 그렇지 않다면 n을 execute 리스트에 append하기
else:
execute.append(n)
print(f"우선순위가 {p}인 프로세스 {n}를 실행한다.")
# execute[location]을 반환
return execute.index(location) + 1
from collections import deque
def solution(priorities, location):
execute = []
num = deque(list(range(len(priorities))))
priorities = deque(priorities)
while len(priorities) > 0:
p = priorities.popleft()
n = num.popleft()
if priorities == deque():
execute.append(n)
break
if max(priorities) > p:
priorities.append(p)
num.append(n)
else:
execute.append(n)
return execute.index(location) + 1
💡 오답 풀이
처음에는 마지막에 priorities 배열에 원소가 하나만 남았을 때의 처리를 잘 못해서 부분점수만 받았따985점)
💡 다른 풀이
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
num을 굳이 만들지 않고 enumerate(priorities)를 해서 원소의 인덱스 = location으로 봤다.
any함수를 써서 priorities 원소의 최댓값과의 비교를 진행한다.
💡 느낀점 or 기억할정보
1. num 큐를 만들 필요 없이, enumerate함수를 쓰면 된다!
2. 나는 모든 프로세스를 실행한 뒤에 해당 location의 실행순서를 파악했는데, 해당 location이 실행되면 답 반환하고 끝내면 되는 거네..!
'알고리즘' 카테고리의 다른 글
[트리] 프로그래머스 level 2 조이스틱 (Python 파이썬) (0) | 2024.04.18 |
---|---|
[트리] 백준 1991번: 트리순회 (Python 파이썬) (1) | 2024.04.18 |
[스택/큐] 프로그래머스 level 2 기능개발 (Python 파이썬) (0) | 2024.03.26 |
[수학] Softeer level 1 위험한 효도 (Python 파이썬) (0) | 2024.03.22 |
[해싱] Softeer level 2 비밀메뉴 (Python 파이썬) (0) | 2024.03.22 |