Python递归查找 parent 的儿子

标签 python dictionary recursion

我实际上正在学习如何应用递归来解决一些现实生活中的问题。比方说,我有一个存储家谱的字典,每个人的 child 都将存储在这个字典中,并且它在树中的级别也将存储在该字典中。我想找出一个家庭的子树并将其存储到一个单独的字典中,所以我必须不断检查这个人是否有 child 。但是,我不知道为什么我的递归函数的新字典只能存储那些没有 child 的人。

dict[1] = [[2,3], 2] #the first one is the children list, the second one is the level in the family tree

newDict = {}
subtree = findSub(dict, 2, 0, newDict)

#my newDict is an empty dictionary, newDict= {}
#level stores the person's level in the tree
def findSub(dict, parent, level, newDict):

    level += 1

    children = dict[parent][0]

    if (len(children) == 0):
        info = [dict[parent][0], level]
        newDict[parent] = info

    else:
        for child in children:
            findSub(dict, child, level, newDict)

    return newDict

最佳答案

However, I don't know why the new dictionary of my recursive function can only store those people that have no child.

def findSub(dict, parent, level, newDict):

    level += 1

    children = dict[parent][0]

    if (len(children) == 0):
    ^^^^^^^^^^^^^^^^^^^^^^^^
        info = [dict[parent][0], level]
   .....

if 检查该元素是否没有子元素。如果它有子元素,您将进一步递归,但在进一步递归之前不会添加该元素。

如果你想保存甚至 parent (最终将导致整个子树),你会做类似的事情

def findSub(dict, parent, level, newDict):

    level += 1

    children = dict[parent][0]
    info = [dict[parent][0], level]
    newDict[parent] = info

    if (len(children) != 0):
        for child in children:
            findSub(dict, child, level, newDict)

    return newDict

关于Python递归查找 parent 的儿子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445063/

相关文章:

python - 导入错误 : No module named 'botocore.parameters'

python - 动态地将数组中的值分配给字典

xcode - Swift 中递归引用自身的函数

带辅助函数的 Python 递归函数

Python:字典的值是字符串列表

python - 通过矩阵查找所有路径

python - 使用 CheckList 和 Hlist 使用 Python 自动检查 Tix 中的子项

python - Numpy 索引异常 : How to subselect from multidimensional array and keep all axes

python - 如何从词干提取中排除某些名称和术语 (Python NLTK SnowballStemmer (Porter2))

javascript - 在带有扩展的 map 中使用 Promise