From 05ffc6e0b716040ee3245384d405f8161b3e82d0 Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Thu, 3 Aug 2023 16:24:22 -0700 Subject: [PATCH] Create trie.py --- tries/trie.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 tries/trie.py diff --git a/tries/trie.py b/tries/trie.py new file mode 100644 index 0000000..c5dd85f --- /dev/null +++ b/tries/trie.py @@ -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)