在递归函数中的变量解包期间,Python“Int对象不可迭代”

问题描述 投票:0回答:1

我有一个递归函数,它通过二叉树移动并计算最左边节点和最右边节点之间的差异。

如果我导航到左边的子节点并且如果我去右边的那个,则计数+ 1,它通过取一个参数“count”来计数-1。

它返回一个元组(countsx,countdx),其中countsx(countdx)是当前计数变量(对于countx和countdx)的最小值(最大值),left子节点返回的countsx(countdx)值和che countx(countdx)从正确的孩子返回的价值。

这是代码。它在递归开始时在标记的行上引发错误“Int类型不可迭代”。

def ausilioes17(tree, count):

    countsx = 0
    countdx = 0

    # If it's a leaf, just return the count parameter
    if not tree.sx and not tree.dx: return count

    if tree.sx:
        # it raises an error here when unpacking
        countsx, dummydx = ausilioes17(tree.sx, count-1) # <-------

    if tree.dx:
        dummysx, countdx = ausilioes17(tree.dx, count+1)

    return min(countsx, dummysx, count), max(countdx, dummydx, count)

if __name__ == "__main__":
    a = Tree() # has just left child (a.sx) and right child (a.dx)
    sx, dx = ausilioes17(a, 0)
    print(str(dx-sx))
python recursion tuples
1个回答
2
投票

你的树最初是空的,所以你正在击中return count,它无法解压缩为两个值

也许你想要return count, count

© www.soinside.com 2019 - 2024. All rights reserved.