본문 바로가기

프로그래밍/Python

Connected Component

반응형
>>> 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