From 7e9fd69cced39d50ff0195a85ec33d19a391b18c Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sun, 30 Jun 2024 12:37:04 +0100 Subject: [PATCH] posts: trie: add search --- content/posts/2024-06-30-trie/index.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/content/posts/2024-06-30-trie/index.md b/content/posts/2024-06-30-trie/index.md index 584e856..968aa0e 100644 --- a/content/posts/2024-06-30-trie/index.md +++ b/content/posts/2024-06-30-trie/index.md @@ -63,3 +63,18 @@ character. The string key will be implicit by the position of a node in the tree: the empty string at the root, one-character strings as its direct children, etc... + +### Search + +An exact match look-up is easily done: we go down the tree until we've exhausted +the key. At that point we've either found a mapped value or not. + +```python +def get(self, key: str) -> T | None: + # Have we matched the full key? + if not key: + # Store the `T` if mapped, `None` otherwise + return self._value + # Otherwise, recurse on the child corresponding to the first letter + return self._children[key[0]].get(key[1:]) +```