Home > Mobile >  Create a Category Tree using python
Create a Category Tree using python

Time:12-03

A category tree is a representation of a set of categories and their parent-child relationships. Each category has a unique name (no two categories have the same name). A category can have a parent category. Categories without a parent category are called root categories.

Need to create a category tree with following description using python programming.

  • To add a category to a category tree :- the name and the parent of the category should be provided.
  • When adding a root category, a null value should be provided as the parent.
  • A call to getChildren method should return the direct children of the specified category in any order.
  • KeyError method should be thrown when adding a category that has already been added anywhere in the CategoryTree or if a parent is specified but does not exist.

Please help me out to solve this problem.

Am new to oops concepts using python, thus unable to clear the problem. A helping hand to solve the problem is much appreciated.

CodePudding user response:

To create a category tree in Python, you can define a CategoryTree class that has the following methods:

  1. add_category(name: str, parent: Optional[str]): This method should add a new category with the given name and parent to the category tree. If a null value is provided as the parent, the category should be added as a root category.
  2. get_children(name: str): This method should return the direct children of the category with the given name in any order.
  3. invalid_argument_exception(name: str): This method should raise an InvalidArgumentException exception when adding a category that has already been added anywhere in the CategoryTree or if a parent is specified but does not exist. Here is an example of how you can implement this CategoryTree class:
class CategoryTree:
    def __init__(self):
        self.categories = {}

    def add_category(self, name: str, parent: Optional[str]):
        if name in self.categories:
            self.invalid_argument_exception(f"Category {name} already exists")

        if parent is not None and parent not in self.categories:
            self.invalid_argument_exception(f"Parent {parent} does not exist")

        self.categories[name] = parent

    def get_children(self, name: str):
        children = []
        for category, parent in self.categories.items():
            if parent == name:
                children.append(category)
        return children

    def invalid_argument_exception(self, message: str):
        raise InvalidArgumentException(message)

In the code above, the CategoryTree class has a dictionary categories that stores the name and parent of each category. The add_category() method first checks if the given category name already exists in the categories dictionary. If it does, it raises an InvalidArgumentException with an appropriate error message. It then checks if the given parent exists in the categories dictionary. If it does not, it raises an InvalidArgumentException with an appropriate error message. Finally, it adds the category to the categories dictionary.

The get_children() method iterates over the categories dictionary and returns all the categories whose parent is the given category name.

The invalid_argument_exception() method simply raises an InvalidArgumentException with the given error message.

You can use this CategoryTree class as follows:

tree = CategoryTree()
tree.add_category("fruit", None)
tree.add_category("vegetable", None)
tree.add_category("apple", "fruit")
tree.add_category("banana", "fruit")
tree.add_category("carrot", "vegetable")
tree.add_category("tomato", "vegetable")

print(tree.get_children("fruit"))  # ["apple", "banana"]
print(tree.get_children("vegetable"))  # ["carrot", "tomato"]

In the code above, we first create a CategoryTree object and add several categories to it. We then print the direct children of the "fruit" and "veget

tree = CategoryTree()
tree.add_category("fruit", None)
tree.add_category("vegetable", None)
tree.add_category("apple", "fruit")
tree.add_category("banana", "fruit")
tree.add_category("carrot", "vegetable")
tree.add_category("tomato", "vegetable")

print(tree.get_children("fruit"))  # ["apple", "banana"]
print(tree.get_children("vegetable"))  # ["carrot", "tomato"]
  • Related