question 263 Inheritance & Composition · easy
The path up a category tree
Product categories form a hierarchy, like classes and their parents: Yoga mats are a kind of Fitness product, which is a kind of Sports product. The catalogue stores it as a dictionary from each category to its parent (None for a top-level category). Write category_path(category, parents), returning the path from the top-level category down to the one asked for, as a website's breadcrumb shows it.
Function
category_path(category, parents)parentsa dictionary from category to parent category, or to None for a top level; every parent named is also a key
Returnsa list from the top-level category to
category itselfRaises
ValueError for a category that isn't in parents, or when following parents loops back to a category already on the pathMust notchange
parentsExamples
callcategory_path('Yoga mats', {'Sports': None, 'Fitness': 'Sports', 'Yoga mats': 'Fitness', 'Home': None, 'Lamps': 'Home'})returns['Sports', 'Fitness', 'Yoga mats']
callcategory_path('Lamps', {'Sports': None, 'Fitness': 'Sports', 'Yoga mats': 'Fitness', 'Home': None, 'Lamps': 'Home'})returns['Home', 'Lamps']
callcategory_path('Home', {'Sports': None, 'Fitness': 'Sports', 'Yoga mats': 'Fitness', 'Home': None, 'Lamps': 'Home'})returns['Home']
callcategory_path('Garden', {'Sports': None, 'Fitness': 'Sports', 'Yoga mats': 'Fitness', 'Home': None, 'Lamps': 'Home'})raisesValueError