Problem 3: Trie (200pts)
Write a function has_path
that takes in a tree t
and a string word
.
It returns True
if there is a path starting from the root,
along which the entries spell out the word. Otherwise, it returns False
.
(This data structure is called a trie, and it has a lot of cool applications!---think autocomplete).
You may assume that every node's label is exactly one character.
def has_path(t, word):
"""Return whether there is a path in a tree where the entries along the path
spell out a particular word.
>>> greetings = tree('h', [tree('i'),
... tree('e', [tree('l', [tree('l', [tree('o')])]),
... tree('y')])])
>>> print_tree(greetings)
h
i
e
l
l
o
y
>>> has_path(greetings, 'h')
True
>>> has_path(greetings, 'i')
False
>>> has_path(greetings, 'hi')
True
>>> has_path(greetings, 'hello')
True
>>> has_path(greetings, 'hey')
True
>>> has_path(greetings, 'bye')
False
"""
assert len(word) > 0, 'no path for empty word.'
"*** YOUR CODE HERE ***"