⚡️algorithm/accepted

[combinations, Counter, 빈도] 프로그래머스 lv2. 메뉴리뉴얼

남남이루 2022. 9. 10. 00:06

문제

from itertools import combinations


def solution(orders, course):
    comb_dic = {long: {} for long in course}
    selected = set()

    for long in course:
        best_num = 2
        for guest in orders:
            comb = list(map(sorted, combinations(guest, long)))
            comb = ["".join(arr) for arr in comb if len(arr) > 0]

            for e in comb:
                if not e:
                    continue
                key = "".join(sorted(e))
                if key in comb_dic[long].keys():
                    comb_dic[long][key] += 1
                    best_num = max(best_num, comb_dic[long][key])
                else:
                    comb_dic[long][key] = 1

        for k, v in comb_dic[long].items():
            if v >= best_num:
                selected.add(k)

    selected = sorted(list(selected))
    return selected

기억할 표현식

cnt = Counter(list) 로 dictionary 형태임.

answer += ["".join(f) for f in cnt if cnt[f] == max(cnt.values())]
cnt.values() # dictionary의 값을 배열로 반환

=> 대체

        selected += [
            "".join(f) for f in comb_dic[long] if comb_dic[long][f] == max(comb_dic[long].values())
        ]
        for k, v in comb_dic[long].items():
            if v >= best_num:
                selected.add(k)