본문 바로가기

카테고리 없음

[프로그래머스/python] 코딩테스트 연습 Lv.2 할인 행사

728x90

문제

입출력 예

Solution

import collections

def solution(want, number, discount):
    answer = 0
    l = []
    
    want_num = {key: value for key, value in zip(want,number)} # 원하는 것 dict로 저장
    want_num = sorted(want_num.items())
    
    for i in range(len(discount)-sum(number)+1):
        d = dict(collections.Counter(discount[i:i+sum(number)])) # 요소 count해 dict로 저장
        l.append(sorted(d.items()))
    
    for i in l:
        if want_num == i:
            answer+=1
    
    return answer

 

1. 사고자하는 품목이 담긴 want 리스트와 그에 대한 개수가 담긴 number 리스트를 하나의 dictionary로 합쳐주고, 이를 key값을 기준으로 오름차순 정렬해준다. -> want_num

* sorted(dict.keys()): keys만 따로 빼서 정렬하고자 할 때 / sorted(dict.items()): keys 기준으로 정렬하되 dict 형태는 유지

 

2. 첫번째 for문에서 할인하는 품목이 날짜순으로 담긴 discount 리스트에서 사고자 하는 품목의 개수만큼 리스트를 자르고, 품목 별로 count하여 이에 대한 dictionary를 만들어주었다. -> l에 모든 dict append

* collections.Counter(list): list 내의 요소를 count하여 이를 collections 형태로 저장 -> dict()를 이용하여 형태 변환

 

3. want_num dict와 l에 담긴 dict을 비교하여 같은 경우가 있으면 원하는 제품을 모두 할인 받을 수 있는 회원등록 날이므로 answer+=1을 해준다.

728x90