【问题标题】:Implementing a category tree实现类别树
【发布时间】:2021-01-10 02:04:04
【问题描述】:

我正在实施一个大陆-国家关系类别图 在我的实现中,一个方法add_country(),作为add_country 的参数,我提供了它所属的国家和大陆的名称,例如add_country(Uganda, Africa)。这会添加一个节点 Africa->Uganda。

如果我传递一个类似的函数,第二个参数为0,例如。 add_country(Asia, 0),它应该将第一个参数添加为类别头或父级。 get_country() 方法应返回属于该大陆(或子大陆)的所有国家/地区的名称。

到目前为止,我已经做到了:

class Node:
    def __init__(self, val):
        self.children = []
        self.value = val

    def add_child(self, val):
        n = Node(val)
        self.children.append(n)

    def print_stat(self):
      print(self.children)
      print(self.value)

class CountryTree:

    def __init__(self):
        self.roots = []


    def add_country(self, country, parent):
      if parent == None:
        root = Node(country)
        self.roots.append(root)
      else:
        par = Node(parent)
        par.add_child(country)



    def get_country(self, parent):
      par = Node(parent)
      return par.children



map = CountryTree()
map.add_country('Asia', None)
map.add_country('China', 'Asia')
map.add_country('Russia', 'Asia')
map.get_country('Asia') #Should return China and Russia

但是运行它会返回一个空数组。

【问题讨论】:

  • 您需要更详细地描述如何它“不工作”。
  • 我已经更新了,先生
  • 请提供一个可运行的minimal reproducible example,目前,您的代码会导致来自map.add_country('China', 'Asia') 调用的NameError: name 'category' is not defined — 不是一个空数组。
  • 有一个小错字,导致这个错误!,我已经更正了,谢谢

标签: python graph tree categories


【解决方案1】:

我认为以下内容可以满足您的要求。大多数重大变化都发生在CountryTree 类。我把你拥有的大陆列表改成了字典。这使得确定一个人是否存在变得容易和快速——这是你的add_country() 方法没有做的事情——这是它的主要问题之一。我还将其名称从 self.roots 更改为 self.continents 以更具描述性。我还为parent 参数提供了None 的默认值,这使得在添加大陆节点时提供它是可选的。

另一个重要的变化是使代码遵循PEP 8 - Style Guide for Python Code 准则,使其更具可读性和可理解性。我强烈建议您自己阅读并关注它们。

class Node:
    def __init__(self, value):
        self.children = []
        self.value = value

    def add_child(self, value):
        self.children.append(Node(value))

    def __repr__(self):
        classname = type(self).__name__
        return (f'{classname}({self.value!r}, {self.children})' if self.children else
                f'{classname}({self.value!r})')

    def print_stat(self):
        print(self.children)
        print(self.value)


class CountryTree:
    def __init__(self):
        self.continents = {}  # Dictionary mapping continents to countries.

    def add_country(self, country, parent=None):
        if not parent:  # Adding a continent?
            continent = country
            self.continents[continent] = Node(continent)
        else:  # Adding a country to a continent.
            continent = self.continents.get(parent, None)
            if not continent:
                raise KeyError(f'No continent named {parent} exists')
            continent.add_child(country)

    def get_country(self, parent):
        continent = self.continents.get(parent, None)
        if not continent:
            raise KeyError(f'No continent named {parent} exists')
        return continent.children


map = CountryTree()
map.add_country('Asia')
map.add_country('China', 'Asia')
map.add_country('Russia', 'Asia')
result = map.get_country('Asia') # Should return China and Russia
print(result)

输出:

[Node('China'), Node('Russia')]

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多