question 149 Advanced Functions & Recursion · medium
One menu row per level
A shop's mega-menu shows one row per level of the category tree: the departments, then the sections inside them, and so on. Write names_at_level(category, level): return the names of every category exactly level steps below category, from left to right. Level 0 is the category itself.
Function
names_at_level(category, level)category
{"name": …, "products": […], "children": [categories of the same shape…]}levela whole number, 0 or more
Returnsa new list of names, in left-to-right order;
[] when the tree is not that deepExamples
callnames_at_level({'name': 'All', 'products': [], 'children': [{'name': 'Electronics', 'products': ['Organic Speaker'], 'children': [{'name': 'Audio', 'products': ['Studio Headphones', 'Pocket Radio'], 'children': [{'name': 'Headphones', 'products': ['Travel Earbuds'], 'children': []}]}, {'name': 'Cameras', 'products': ['Action Cam'], 'children': []}]}, {'name': 'Home', 'products': ['Deluxe Vase', 'Nordic Candle'], 'children': []}]}, 1)returns['Electronics', 'Home']
callnames_at_level({'name': 'All', 'products': [], 'children': [{'name': 'Electronics', 'products': ['Organic Speaker'], 'children': [{'name': 'Audio', 'products': ['Studio Headphones', 'Pocket Radio'], 'children': [{'name': 'Headphones', 'products': ['Travel Earbuds'], 'children': []}]}, {'name': 'Cameras', 'products': ['Action Cam'], 'children': []}]}, {'name': 'Home', 'products': ['Deluxe Vase', 'Nordic Candle'], 'children': []}]}, 2)returns['Audio', 'Cameras']
callnames_at_level({'name': 'All', 'products': [], 'children': [{'name': 'Electronics', 'products': ['Organic Speaker'], 'children': [{'name': 'Audio', 'products': ['Studio Headphones', 'Pocket Radio'], 'children': [{'name': 'Headphones', 'products': ['Travel Earbuds'], 'children': []}]}, {'name': 'Cameras', 'products': ['Action Cam'], 'children': []}]}, {'name': 'Home', 'products': ['Deluxe Vase', 'Nordic Candle'], 'children': []}]}, 0)returns['All']