Count names, not visits, because one name can reach a node twice
add_suffixes adds 1 every time a name's walk passes a node, and one name can pass the same node twice. Three toys show it, ["yoyo", "kayak", "pole"]. Here is yoyo going in:
So yo gets 2 from yoyo alone. Here are the counts both ways:
| Fragment: the names with it | Count by visits | Count by names |
|---|---|---|
| y: yoyo, kayak | 3 | 2 |
| yo: yoyo | 2 | 1 |
| o: yoyo, pole | 3 | 2 |
| k: kayak | 2 | 1 |
| a: kayak | 2 | 1 |
Counting visits gives yoyo the answer oy and kayak the answer ka. Both are wrong.
yo is in no other name, but it appears twice in yoyo, so its count is 2 and the query walks past it. kayak has two ks and nobody else has one, yet k counts 2.
The count has to mean names. So a name adds 1 to a node once, however often it gets there. The right answers are yo and k.
To remember which nodes one name has counted, keep a set for the length of one insert. A node is a dict, and a dict can't go in a set: it's mutable, so it's unhashable, as in the hash-maps lesson.
Its id can go in a set. id(node) is an integer that's unique to that object and stays the same while the object exists. Every node stays alive in the trie, so no id gets reused during the insert.
In the editor, finish add_name(trie, name). It adds three names and prints two counts: yo, twice in one name, and kit, in two names.