시간 초과가 떠서 풀지 못했던 문제다. 아마 for문을 너무 많이 사용한 것 같다.
from itertools import combinations
def solution(orders, course):
answer = []
menu = set()
for o in orders:
o = list(o)
for i in o:
menu.add(i)
menu = list(menu)
menu.sort()
for n in course:#course
result = list(combinations(menu, n))
stack = []
maxcount = 0
for r in result:#combinations
count = 0
for o in orders:
part = True
for i in range(n):
if not r[i] in o:
part = False
if part: count += 1
if count > 1:
if count > maxcount:
stack = []
stack.append(r)
maxcount = count
elif count == maxcount:
stack.append(r)
for s in stack:
answer.append("".join(s))
answer.sort()
return answer
수정 후
from itertools import combinations
def solution(orders, course):
answer = []
for n in course:
order_combs = []
comb_count = {}
for o in orders:
order_combs.extend(list(combinations(sorted(o), n)))
for o in order_combs:
ord_string = "".join(o)
if ord_string in comb_count:
comb_count[ord_string] += 1
else:
comb_count[ord_string] = 1
for o in comb_count:
if comb_count[o] == max([comb_count[o] for o in comb_count]) and comb_count[o] > 1:
answer.append(o)
answer.sort()
return answer
딕셔너리를 적절히 사용하자.....
string에는 sort()함수를 사용할 수 없지만 sorted()함수는 사용할 수 있다.