CodingTest/프로그래머스

[프로그래머스] 할인 행사

Jay_J 2024. 8. 3. 12:21

 

- 문제를 보면 각 요소의 출현 횟수와 배열을 한번에 10칸씩 검사하며 확인을 해야한다. 그래서 Counter와 sliding window가 생각났다.

 

from collections import Counter

def solution(want, number, discount):
    stuff_dict = {}
    days = 10
    res = 0
    
    for i in range(len(want)):
        stuff_dict[want[i]] = number[i]
        
    for i in range(len(discount) - days + 1):
        counts = Counter(discount[i:i+days])
        
        if all(counts[key] >= val for key, val in stuff_dict.items()):
            res += 1
    return res

 

-우선, Counter를 이용하기 위해 from collections import Counter를 해준다.

 

- 그리고 선언한 딕셔너리에 원하는 물건과 원하는 갯수를 매핑 해준다.

 

- 여기서 sliding window를 사용했는데, discount배열에서 이제 각 루프를 돌 때마다 10개씩 한번에 출현 횟수를 세어야 한다. 

 

"all"

`all` 함수는 파이썬 내장 함수로, 반복 가능한(iterable) 객체의 모든 요소가 참(True)인 경우에만 `True`를 반환합니다. 그렇지 않으면 `False`를 반환합니다. 일반적으로 리스트, 튜플, 세트, 딕셔너리 등과 같은 반복 가능한 객체에서 사용됩니다.

기본 사용법

all(iterable)


- `iterable`: 리스트, 튜플, 세트, 딕셔너리 등 반복 가능한 객체.

예제

1. 리스트의 모든 요소가 참인지 확인

# 모든 요소가 참일 때
print(all([True, True, True]))  # Output: True

# 하나라도 거짓이 있을 때
print(all([True, False, True]))  # Output: False

# 빈 리스트 (빈 반복 가능한 객체는 항상 True를 반환)
print(all([]))  # Output: True



2. 문자열의 모든 문자가 알파벳인지 확인

words = ["apple", "banana", "cherry"]

# 모든 단어가 알파벳 문자로만 구성되어 있는지 확인
print(all(word.isalpha() for word in words))  # Output: True

# 문자열 중 하나가 숫자를 포함할 때
words = ["apple", "banana", "cherry123"]
print(all(word.isalpha() for word in words))  # Output: False


3. 딕셔너리 값이 모두 양수인지 확인

scores = {"math": 90, "science": 85, "english": 88}

# 모든 점수가 양수인지 확인
print(all(score > 0 for score in scores.values()))  # Output: True

# 점수 중 하나가 음수일 때
scores = {"math": 90, "science": -85, "english": 88}
print(all(score > 0 for score in scores.values()))  # Output: False


설명

- `all(counts[key] >= val for key, val in stuff_dict.items())`:
  - `stuff_dict.items()`는 (key, value) 쌍을 반환합니다.
  - `counts[key] >= val`은 현재 윈도우 내의 제품 수량이 원하는 수량 이상인지를 확인합니다.
  - `all` 함수는 이러한 조건이 모든 제품에 대해 참인지 확인합니다. 모든 조건이 참이면 `True`를 반환하고, 그렇지 않으면 `False`를 반환합니다.