🔅코딩테스트 공부🔅/❗프로그래머스(Lv.2)
[프로그래머스] Level2 할인 행사(python)
윤무무
2023. 3. 8. 13:12
https://school.programmers.co.kr/learn/courses/30/lessons/131127
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 해결 방법
dictionary + 슬라이딩 윈도우를 이용해서 문제를 풀었는데,
Counter를 이용하면 불필요한 절차 없이 쉽게 구할 수 있다.
- 슬라이딩 윈도우
def solution(want, number, discount):
want_dic = {} #원하는 할인 제품
new_dic = {} #투 포인터
for i in range(len(want)): #원하는 제품 목록 딕셔너리로 만들기
want_dic[want[i]] = number[i]
new_dic[want[i]] = 0
for i in discount[:10]: #index 0 ~ 10일(index 9)까지 살 수 있는 물품 카운팅
if i in new_dic:
new_dic[i] += 1
cnt = 0 #모두 할인 받을 수 있는 날의 수
start = 0
end = 9
while end != len(discount):
if new_dic == want_dic: #연속해서 모두 할인 받을 수 있으면 카운팅
cnt+= 1
#start와 end로 이동하며 슬라이드 윈도우 구현
end+=1
if end == len(discount):
return cnt
if discount[end] in new_dic:
new_dic[discount[end]] += 1
if discount[start] in new_dic:
new_dic[discount[start]]-=1
start+=1
- Counter
from collections import Counter
def solution(want, number, discount):
want_dic = {}
cnt = 0
for i in range(len(want)):
want_dic[want[i]] = number[i]
for i in range(len(discount)-9):
if want_dic == Counter(discount[i:i+10]):
cnt+=1
return cnt
메모
Counter 변환 된 자료 == dictionary 자료는 변환없이 바로 연산 가능