From 55982909d2ce8b7f3cc67de3d97f1982316ecc41 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sun, 30 Jun 2024 12:37:21 +0100 Subject: [PATCH] posts: trie: add insertion --- content/posts/2024-06-30-trie/index.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/content/posts/2024-06-30-trie/index.md b/content/posts/2024-06-30-trie/index.md index 968aa0e..b8e4679 100644 --- a/content/posts/2024-06-30-trie/index.md +++ b/content/posts/2024-06-30-trie/index.md @@ -78,3 +78,22 @@ def get(self, key: str) -> T | None: # Otherwise, recurse on the child corresponding to the first letter return self._children[key[0]].get(key[1:]) ``` + +### Insertion + +Adding a new value to the _Trie_ is similar to a key lookup, only this time we +store the new value instead of returning it. + +```python +def insert(self, key: str, value: T) -> bool: + # Have we matched the full key? + if not key: + # Check whether we're overwriting a previous mapping + was_mapped = self._value is None + # Store the corresponding value + self._value = value + # Return whether we've performed an overwrite + return was_mapped + # Otherwise, recurse on the child corresponding to the first letter + return self._children[key[0]].insert(key[1:], value) +```