https://school.programmers.co.kr/learn/courses/30/lessons/42890
from itertools import combinations
def combine_keys(keys, index):
combine_keys_list = []
for i in range(len(keys[0])):
combine_key = ""
for j in range(len(index)):
combine_key += keys[index[j]][i]
combine_keys_list.append(combine_key)
return combine_keys_list
def solution(relation):
res = 0
keys = []
for i in range(len(relation[0])):
tmp = []
for j in range(len(relation)):
tmp.append(relation[j][i])
keys.append(tmp)
not_unique_keys = []
for i in range(len(keys)):
if len(set(keys[i])) == len(keys[i]):
res += 1
else:
not_unique_keys.append(i)
candidate_keys = [] # 1 2 3
for i in range(2, len(not_unique_keys)+1):
candidate_keys.extend(combinations(not_unique_keys, i))
candidate_keys.sort(key=len)
exclude_keys = []
for c in candidate_keys:
flag = False
for ex in exclude_keys:
if ex & set(c) == ex:
flag = True
break
if not flag and len(set(combine_keys(keys, c))) == len(combine_keys(keys, c)):
res += 1
exclude_keys.append(set(c))
return res
1. 칼럼별로 배열 다시 만들기!
keys = []
for i in range(len(relation[0])):
tmp = []
for j in range(len(relation)):
tmp.append(relation[j][i])
keys.append(tmp)
2. 먼저 단독으로 유일성을 만족하는 키 걸러내기
not_unique_keys = []
for i in range(len(keys)):
if len(set(keys[i])) == len(keys[i]):
res += 1
else:
not_unique_keys.append(i)
3. 단독으로 유일성이 만족하지 않는 키들에 대해서 모든 조합을 구하기
candidate_keys = []
for i in range(2, len(not_unique_keys)+1):
candidate_keys.extend(combinations(not_unique_keys, i))
candidate_keys.sort(key=len)
4. 최소성 검증
def combine_keys(keys, index):
combine_keys_list = []
for i in range(len(keys[0])):
combine_key = ""
for j in range(len(index)):
combine_key += keys[index[j]][i]
combine_keys_list.append(combine_key)
return combine_keys_list
exclude_keys = []
for c in candidate_keys:
flag = False
for ex in exclude_keys:
if ex & set(c) == ex:
flag = True
break
if not flag and len(set(combine_keys(keys, c))) == len(combine_keys(keys, c)):
res += 1
exclude_keys.append(set(c))