from itertools import combinations
from collections import defaultdict
def solution(orders, course):
answer = []
for o in range(len(orders)):
orders[o]=''.join(list(sorted(orders[o])))
for c in course:
c_set=defaultdict(int)
for order in orders:
for cb in combinations(order,c):
c_set[''.join(cb)]+=1
mx_cnt = 2
mx_combs = []
for key,cnt in c_set.items():
if mx_cnt < cnt:
mx_cnt =cnt
mx_combs=[key]
elif mx_cnt==cnt:
mx_combs.append(key)
answer.extend(mx_combs)
return sorted(answer)
import collections
import itertools
def solution(orders, course):
result = []
for course_size in course:
order_combinations = []
for order in orders:
order_combinations += itertools.combinations(sorted(order), course_size)
most_ordered = collections.Counter(order_combinations).most_common()
result += [ k for k, v in most_ordered if v > 1 and v == most_ordered[0][1] ]
return [ ''.join(v) for v in sorted(result) ]
combinations.Counter
dict으로 숫자 세는 거 대신 할 수 있음def countLetters(word): counter = {} for letter in word: if letter not in counter: counter[letter] = 0 counter[letter] += 1 return counter countLetters('hello world')) # {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
위 코드를 아래와 같이 만들 수 있다.
from collections import Counter Counter('hello world') # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
데이터의 개수가 많은 순으로 정렬된 배열을 리턴하는 most_common이라는 메서드를 제공하고 있습니다.
from collections import Counter Counter('hello world').most_common() # [('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]
.most_common(k)
하면 k번째까지 반환해준다.