[Lv2]프로그래머스 - 프린터(python) + any, all 활용하기

건너별·2021년 12월 5일
0

algorithm

목록 보기
12/27

프로그래머스 예제 : 프린터

ideation💡

  • 첫 순서 정보를 기억해야 하기 때문에 enumerate() 사용하여 인덱스정보 저장
  • 큐 를 굳이 안써도 코딩 가능.
  • any를 쓰면 매우 간결한 코드로 변신함. 아래 두 코드를 비교해 보자.

any를 쓰지 않은 코드 : max() 또는 min() 함수를 쓸 때, 빈 리스트일 때 에러가 나므로 예외처리를 해주었다.

from collections import deque
def solution(priorities, location):
    priorities=[(i,pri) for i, pri in enumerate(priorities)]
    # print(priorities)
    que=deque(priorities)
    order = []
    while que:
        
        pri = que.popleft()  
        # print(pri)
        if len(que)!=0:                                 #길이기 0이 아닐때 max 함수 쓴다
            if pri[1] < max(map(lambda x: x[1],que)):
                que.append(pri)

            elif pri[1]>= max(map(lambda x: x[1],que)):
                order.append(pri)
                if pri[0]==location:
                    return order.index(pri)+1
        else:                                           #예외처리.max 함수 없음
            order.append(pri)
            if pri[0]==location:
                return order.index(pri)+1

any를 쓴 코드 : 예외처리 해 줄 필요 없음

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, all : iterable한 객체와 특정 값과 비교할 때 유용

  • max 함수는 빈 리스트를 인자로 받을 경우 런타임 에러가 남. 이것을 방지하기 위함

  • ex) 리스트 값 중 하나라도 5보다 크다면?

any() : OR gate

  • 하나라도 True 라면 True 를 리턴
  • list comprehension 형태로 사용 가능
a= [1,2,3,4,5]

any(0 > i for i in a)

>>> False

any(2 > i for i in a)

>>> True  # 1보다 크니까

any(6 > i for i in a)

>>> True

all()

  • 모든 값이 true여야 true를 리턴
  • list comprehension 형태로 사용 가능
all(0>i for i in a)

>>> False

all(2>i for i in a)

>>> False # 1보다 커도 다른것보단 작아서

all(6>i for i in a)
>>> True  # 모든 것들보다 큼
profile
romantic ai developer

0개의 댓글