For the comma in
("Yonkers",)
see the
comma
operator.
"""
The first item in each tuple is a string.
The remaining items, if any, are tuples.
"""
import sys
tree = \
("United States",
("New York",
("Westchester",
("Yonkers",),
("Hastings",),
("Dobbs Ferry",)
),
("Putnam",
("Garrison",),
("Cold Spring",)
),
("Dutchess",
("Poughkeepsie",)
)
),
("New Jersey",
("Bergen",),
("Hudson",),
("Essex",)
),
("Connecticut",)
)
def printTree(t, level = 0):
"Print the tree whose root is t. Indent the tree by 4 * level spaces."
assert type(t) == tuple and len(t) >= 1 and type(t[0]) == str \
and type(level) == int and level >= 0
print(f'{4 * level * " "}{t[0]}')
for child in t[1:]:
printTree(child, level + 1)
def find(name, t):
"Return the tuple with the given name, or None if not found"
assert type(name) == str \
and type(t) == tuple and len(t) >= 1 and type(t[0]) == str
if name == t[0]:
return t
for child in t[1:]:
r = find(name, child)
if r:
return r
return None
b = bool(find("Putnam", tree))
print("Could we find Putnam?", b)
print()
printTree(tree)
sys.exit(0)
Could we find Putnam? True
United States
New York
Westchester
Yonkers
Hastings
Dobbs Ferry
Putnam
Garrison
Cold Spring
Dutchess
Poughkeepsie
New Jersey
Bergen
Hudson
Essex
Connecticut