Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
recursive solution solution in Clear category for Tree Walker by kurosawa4434
def tree_walker(tree, target):
if tree == target:
return 1
if not isinstance(tree, (dict, list)):
return 0
if isinstance(tree, dict):
tree = tree.values()
return sum(tree_walker(leaf, target) for leaf in tree)
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"
assert tree_walker([], []) == 1, 'ex01'
assert tree_walker({3: {1: 'A', 2: {1: 'A', 2: 'B'}}, 4: {1: 'A', 2: 'B'}}, {1: 'A', 2: 'B'}) == 2
print("Coding complete? Click 'Check' to earn cool rewards!")
Jan. 15, 2020
Comments: