Create trie.py

This commit is contained in:
marina 2023-08-03 16:24:22 -07:00 committed by GitHub
parent eb7a7af574
commit 05ffc6e0b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

30
tries/trie.py Normal file
View File

@ -0,0 +1,30 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
class Trie:
def __init__(self):
self.root = {}
def insert(self, word: str) -> None:
node = self.root
for c in word:
if c not in node:
node[c] = {}
node = node[c]
node['$'] = None
def match(self, seq, prefix=False) -> bool:
node = self.root
for c in seq:
if c not in node:
return False
node = node[c]
return prefix or ('$' in node)
def search(self, word: str) -> bool:
return self.match(word)
def starts_with(self, prefix: str) -> bool:
return self.match(prefix, True)