반응형
>>> data = [("ㄱ","ㄴ"),
("ㄴ","ㄷ"),
("ㄷ","ㄱ"),
("ㄱ","ㄴ"),
("ㄹ","ㅁ"),
("ㅂ","ㅅ"),
("ㅇ","ㄹ")]
>>> data
[('ㄱ', 'ㄴ'), ('ㄱ', 'ㄷ'), ('ㄴ', 'ㄷ'), ('ㄹ', 'ㅁ'), ('ㄹ', 'ㅇ'), ('ㅂ', 'ㅅ')]
>>> class ConnectedGroups:
def __init__(self):
self.groups = [] # groups remain mutually exclusive
def add(self, e):
set_e = set(e)
overlap_index = []
for i, g in enumerate(self.groups):
if set_e & g:
overlap_index.append(i)
if overlap_index:
self.groups[0] = self.groups[0]|set_e
for i in overlap_index[1:]:
self.groups[0] = self.groups[0]|self.groups[i]
self.groups[i] = []
self.groups = [ g for g in self.groups if g ]
else:
self.groups.append(set_e)
def view(self):
print(self.groups)
>>> r = ConnectedGroups()
>>> for e in data:
r.add(e)
r.view()
[{'ㄴ', 'ㄱ'}]
[{'ㄴ', 'ㄱ', 'ㄷ'}]
[{'ㄴ', 'ㄷ', 'ㄱ'}]
[{'ㄴ', 'ㄷ', 'ㄱ'}, {'ㄹ', 'ㅁ'}]
[{'ㄴ', 'ㄹ', 'ㅇ', 'ㄷ', 'ㄱ'}, {'ㄹ', 'ㅁ'}]
[{'ㄴ', 'ㄹ', 'ㅇ', 'ㄷ', 'ㄱ'}, {'ㄹ', 'ㅁ'}, {'ㅂ', 'ㅅ'}]
728x90
'프로그래밍 > Python' 카테고리의 다른 글
카마이클 수 (0) | 2021.04.08 |
---|---|
파이썬 xlrd.biffh.XLRDError: Excel xlsx file; not supported (0) | 2021.03.14 |
파이썬초보 : 숫자계단 (0) | 2021.02.04 |
엘라스틱서치 elasticsearch-dsl 에서 시간조건을 주어 검색하는 방법 (0) | 2021.01.20 |
[파이썬초보] TypeError: 'NoneType' object is not subscriptable (0) | 2021.01.20 |