【问题标题】:Recursion method in a class类中的递归方法
【发布时间】:2018-12-31 22:36:13
【问题描述】:

我们开始研究 OOP,我们有一些问题要解决:

'all_illnesses' 是一个诊断器类的方法。类的变量是一个节点,它是树的根。这棵树的叶子有字符串数据。我们知道这棵树中的每个节点都有 0 或 2 个孩子。现在,我们必须实现 'all_illnesses' 的方法,以便它返回由该树的叶子表示的字符串列表。同一个字符串可以显示不止一次,所以列表必须从最常显示的字符串中排序。

这是我的实现,我认为它存在一些问题: 我不确定递归,因为我在递归方面真的很糟糕。 其次,我不知道如何将这个字典以排序的方式传输到列表中。

所以, 我的递归有什么问题? 以及如何以排序方式将此字典传输到列表中?

我们不能使用模块来解决问题。

def all_illnesses(self):
    """"""
    ill_dict = dict()

    def all_ill_helper(node):
        """"""
        if node.getpos() is None:
            if node.getdate() in ill_dict:
                ill_dict[node.getdata()] += 1
            else:
                ill_dict.update({node.getdata(), 0})
        else:
            all_ill_helper(node.getpos())
            all_ill_helper(node.getneg())

    all_ill_helper(self.root)

【问题讨论】:

  • 您具体要问什么?不清楚。
  • 我的递归有什么问题?如何以排序方式将此字典传输到列表中? @Carcigenicate
  • 这行得通吗?如果不是,错误是什么?你有示例输入/输出吗?
  • 这并不能帮助我理解将字符串传输到排序列表中的方式。 @meowgoesthedog

标签: python python-3.x dictionary recursion


【解决方案1】:

除了@Barmar 指出的node.getdate 错字,您的递归看起来确实不错。排序并不难,但您需要使用 key 函数,该函数使用 ill_dict 中的出现计数来对疾病进行排序,然后以相反的顺序将其取回:

def all_illnesses(self):

    ill_dict = dict()

    def all_illnesses_recursive(node):

        if node.getpos() is None:  # no children if one child missing
            data = node.getdata()

            if data in ill_dict:
                ill_dict[data] += 1
            else:
                ill_dict[data] = 1
        else:
            all_illnesses_recursive(node.getpos())
            all_illnesses_recursive(node.getneg())

    all_illnesses_recursive(self.root)

    # reverse sort keys by value, i.e. most common disease first
    return sorted(ill_dict, key=ill_dict.get, reverse=True)

我知道你不能使用 Python 模块。 collections 中的defaultdict 类会在您可以使用模块时稍微简化此代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2015-08-21
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多