Programmers_프로세스

HKTUOHA·2023년 9월 1일
0

알고리즘 문제

목록 보기
7/15
post-thumbnail

📌문제

https://school.programmers.co.kr/learn/courses/30/lessons/42587



📌나의 코드

from collections import deque

def solution(priorities, location):
    que = deque()
    for p, l in enumerate(priorities):  # (인덱스, 우선순위)라서 
        que.append((p, l))              # (l, p)여야 함

    cnt = 0
    while True:
        MAX = max(que, key = lambda x: x[1])
        if que[0] == MAX:
            if que[0][0] == location:
                cnt += 1
                break
            que.popleft()
            cnt += 1
        else:
            que.rotate(-1)
            
    return cnt

실행 결과



📌다른 사람의 풀이

1. any() 사용

def solution(priorities, location):
    que = [(l, p) for l, p in enumerate(priorities)]
    cnt = 0
    while True:
        item = que.pop(0)
        if any(item[1] < q[1] for q in que):
            que.append(item)
        else:
            cnt += 1
            if item[0] == location:
                return cnt
  • que의 요소들 중 하나라도 우선순위가 맨 앞의 우선순위보다 높으면 que의 뒤에 넣는다
any(item[1] < q[1] for q in que):
	que.append(item)

✏️함수 any()

자료 요소들이 다 False면 False, 하나라도 True면 True

🔎any() 예

  • Boolean
l = [False, False, True]
print(any(l))              # True
l = [False, False]
print(any(l))              # False
  • List / Tuple / Set
l = [4, 5, 6]
print(any(l))              # True
t = (0, 0, False)
print(any(t))              # False
s = {1, 0, 3, False}
print(any(s))              # True
# Empty
l, t, s = [], (), {}
print(any(l), any(t), any(s))  # False False False
  • Dictionary
d = {1: "Hello", 0: "Hi"}
print(any(d))             # True
d = {False: "Hello", 0: "Hi"}
print(any(d))             # False
d = {}
print(any(d))             # False
  • String
s = "Hi"
print(any(s))            # True
s = "0"
print(any(s))            # True
s = ""
print(any(s))            # False
  • 조건식
l = [3, 5, 7, 8, 12]
condition = any(i > 10 for i in l)
print(condition)                    # True
  • 반복문으로 만드는 any 함수
def my_any(l):
	for item in l:
    	if item:
        	return True
    return False

x = [3, 2, 1]
print(my_any(x))        # True
y = []
print(my_any(y))        # False

참고



2. 같은 알고리즘, 더 효율적인 코드

from collections import deque

def solution(priorities, location):
    que = deque((p, l) for l, p in enumerate(priorities))
    print(que)
    
    cnt = 0
    while True:
        item = que.popleft()
        if que and max(que)[0] > item[0]:
            que.append(item)
        else:
            cnt += 1
            if item[1] == location:
                break
                
    return cnt

  • 내 경우처럼 (위치, 우선순위)로 큐를 만드는 것보다 (우선순위, 위치)로 큐를 만들어 사용하는 것이 우선순위의 최댓값을 비교하는 데 더 효율적이다.
    - 나는 lambda를 사용해 요소의 두번째 값을 기준으로 최댓값을 찾으려고 함, 비효율적
  • rotate( )를 사용하는 것보다 앞에서 뺀 요소를 뒤에 넣는 것이 더 효율적이다.
profile
공부 기록

0개의 댓글