3월, 2017의 게시물 표시

[알고리즘] 파이썬으로 Trie 구현하기(2)

이미지
 1편에 이어 2편이다. 지난 장에서는 trie의 간단한 개념과 생성과 입력 기능에 대해 알아보았다. 이번 편에서는 조회와 삭제에 대해 알아보도록 하겠다. 접두어로 검색  Trie의 가장 큰 장점이라고 생각하는 접두어 검색 기능이다. 단어의 일부분으로 전체단어를 검색할 수 있다. 예를들어 trie에 gold, good, gerald를 저장한 다음 검색어에 g를 입력하면 gold, good, gerald를 모두 검색할 수 있다. 이런 기능은 검색어 자동완성에 쓰인다고 한다. 우선 검색 부분의 코드를 보도록 하겠다. def search_with_prefix(self, prefix): words = list() if prefix is None: raise ValueError('Requires not-Null prefix') top_node = self.head for letter in prefix: if letter in top_node.children: top_node = top_node.children[letter] else: return words if top_node == self.head: queue = [node for key, node in top_node.children.items()] else: queue = [top_node] while queue: current_node = queue.pop() if current_node.data is not None: words.append(current_node.data) queue = [node f...