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
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
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 반환