[프로그래머스] 할인 행사 - Python
문제
아이디어
맵 자료형으로 풀 수 있는 간단한 문제이다.
- 정현이가 원하는 아이템과 수량을 딕셔너리로 저장한다.
1
want = {w: n for w, n in zip(want, number)}
- 주어진 할인 정보
discount
를 10일씩 탐색한다.
10일 간의 (할인 제품, 수량)이 원하는 수량과 모두 일치하면answer
를 증가한다.1 2 3
for i in range(len(discount)-9): if all(discount[i:i+10].count(item) == cnt for item, cnt in want.items()): answer += 1
위는 all() 메서드를 활용한 것이고, 이를 풀어서 반복문으로 작성하면 아래와 같다.
1 2 3 4 5 6
for i in range(len(discount)-9): for item, cnt in want.items(): if discount[i:i+10].count(item) != cnt: break else: answer += 1
전체 코드
1
2
3
4
5
6
7
8
9
from collections import defaultdict
def solution(want, number, discount):
answer = 0
want = {w: n for w, n in zip(want, number)}
for i in range(len(discount)-9):
if all(discount[i:i+10].count(item) == cnt for item, cnt in want.items()):
answer += 1
return answer
This post is licensed under CC BY 4.0 by the author.