[Python] any(), all() 함수 알아가기

강주형·2023년 1월 10일
0

파이썬 문법

목록 보기
1/2

프로그래머스 레벨2 (스택/큐)
프린터

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


내 풀이

# 프린터

from collections import deque

def solution(priorities, location):
    order = list(range(len(priorities)))
    q1 = deque(priorities)
    q2 = deque(order)
    cnt = 0
    while q1:
        chk = 0
        now = q1.popleft()
        now_order = q2.popleft()
        for q in q1:
            if q > now:
                q1.append(now)
                q2.append(now_order)
                chk = 1
                break
        if chk == 1:
            continue
        cnt += 1
        if now_order == location:
            return cnt

타인 풀이

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

차이점

  • deque를 두 번 쓰지 않고 list comprehension 사용해서 tuple로 묶음
  • q1을 순회할 때 반복문을 사용하지 않고, if any()로 처리함

any('boolean' for 반복문)
- 반복문 돌다가 'boolean'이 하나라도 True일 때, True 반환
- 반복문 돌다가 'boolean'이 전부 False일 때, False 반환
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

all('boolean' for 반복문)
- 반복문 돌다가 'boolean'이 전부 True일 때, True 반환
- 반복문 돌다가 'boolean'이 하나라도 False일 때, False 반환
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

참고해서 내 코드 개선해보기

내 풀이 (개선)

# 프린터 (타인 코드 참고 후 개선)

from collections import deque

def solution(priorities, location):
    order = list(range(len(priorities)))
    q1 = deque(priorities)
    q2 = deque(order)
    cnt = 0
    while q1:
        now = q1.popleft()
        now_order = q2.popleft()
        if any(q > now for q in q1):
            q1.append(now)
            q2.append(now_order)
        else:
            cnt += 1
            if now_order == location:
                return cnt
profile
Statistics & Data Science

0개의 댓글