From 9afd83ca4da8b94228613292862fb47b19a3a8b8 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sun, 30 Jun 2024 12:37:21 +0100 Subject: [PATCH] posts: trie: add addition --- 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..92a9ff8 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:]) ``` + +### Addition + +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) +```