Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Tree Walker by colinmcnicholl
def countem(node, target):
'''Count occurences of the target in list.'''
if node == target:
return 1
if isinstance(node, list):
return sum(countem(subnode, target) for subnode in node)
if isinstance(node, dict):
return sum(countem(subnode, target) for subnode in node.values())
return 0
def path_to(target, node):
if target == node:
return f' -> {target!r}'
elif isinstance(node, list):
for i, subnode in enumerate(node):
path = path_to(target, subnode)
if path:
return f'[{i}]{path}'
elif isinstance(node, dict):
for key, subnode in node.items():
path = path_to(target, subnode)
if path:
return f'[{key!r}]{path}'
return ''
def tree_walker(tree, target):
"""Inputs: Two argument. The first, 'tree', is an arbitrary finite
tree data structure and the second 'target' is any type of
[int, str, list, dict].
Output: The number (integer) of the leaves or subtrees that are equal
to the given target.
"""
out = countem(tree, target)
return out
if __name__ == '__main__':
print("Example:")
print(tree_walker([1, "2", 3, [[3], 1, {1: "one"}]], 1))
# These "asserts" are used for self-checking and not for an auto-testing
assert tree_walker([1, "2", 3, [[3], 1, {1: "one"}]], 1) == 2, "1st"
assert tree_walker({"one": 1, "two": [{1: "one", 2: "two"}, 1, "1", "one"]}, 1) == 2, "2nd"
assert tree_walker({"one": [1, 2], "two": [{1: "one", 2: "two"}, [1, 2], "1", "one"]}, [1, 2]) == 2, "3rd"
assert tree_walker(5, 5) == 1, "4th"
assert tree_walker([5, 6, 2, "1"], 1) == 0, "5th"
assert tree_walker([[dict()], [[[3], [3, 5]]], [], []], 3) == 2, "6th"
assert tree_walker([{1: "one"}, {2: "two"}, "two", ["two", {"two": "one"}]], "two") == 3, "7th"
print("Coding complete? Click 'Check' to earn cool rewards!")
Jan. 27, 2020
Comments: