【问题标题】:Python 2.7: Using list.append in function argumentsPython 2.7:在函数参数中使用 list.append
【发布时间】:2015-08-22 20:50:28
【问题描述】:

我正在尝试编写代码来打印二叉树中的路径,该路径加起来就是传递给函数的总和。对于一个简单的测试用例,以下代码一直失败:

最后执行的输入:Binary Tree = [1], sum = 1

运行时错误消息: Line 26: TypeError: object of type 'NoneType' has no len()

标准输出:None None

我无法理解leftPathrightPath 是如何变成None 的。我根本不返回 None。

'''
Created on Aug 12, 2015

@author: debpriyas
'''

class BTNode(object):
    '''
    classdocs
    '''
    def __init__(self,value, leftBTNode=None, rightBTNode=None):
        '''
        Constructor
        '''
        self.value = value
        self.left = leftBTNode
        self.right = rightBTNode
        # To deal with duplicate values in BST. 
        self.count = 1

def pathSum(root, sum):
    return pathSumHelper( root, sum, [])

def pathSumHelper(root, sum, path):

    if root == None:
        if sum == 0:
            return path
        else:
            return []

    leftPath = pathSumHelper(root.left, sum-root.value, path.append(root.value))
    rightPath = pathSumHelper(root.right, sum-root.value, path.append(root.value))
    print leftPath, rightPath
    if len(leftPath) == 0 and len(rightPath) == 0:
        return []

    if len(leftPath) == 0:
        return [rightPath]
    elif len(rightPath) == 0:
        return [leftPath]
    return [leftPath, rightPath]


if __name__ == '__main__':
    root = BTNode(1)

    print pathSum(root, 1)

【问题讨论】:

  • 请尝试将您截取的代码转换为minimal, complete, and verifiable example
  • @das-g:更改的代码可以在隔离系统上运行。代码是最小的并且更早完成。现在我猜它是可以验证的。

标签: list function python-2.7 append


【解决方案1】:

问题出在这里:

leftPath = pathSumHelper(root.left, sum-root.value, path.append(root.value))
rightPath = pathSumHelper(root.right, sum-root.value, path.append(root.value))

您正在使用 path.append(root.value),然后使用从“append”函数调用返回的内容作为 pathSumHelper 函数中的参数,该函数是一个 NoneType(它就地修改对象,并返回无,这就是为什么当你从控制台调用它时,它什么也不返回)。

相反,你需要在函数调用之前使用append,然后在函数中使用路径或者做

path + [root.value]

在你的函数调用中,所以它会返回一个实际的列表。

我建议您执行以下操作,因为您想在我假设的地方修改“路径”。

path.append(root.value)
leftPath = pathSumHelper(root.left, sum-root.value, path)

总和为0的任何东西都会返回Nonetype,这将在len调用期间导致TypeError。

一个简单、可验证、可重现的例子是:

>>>def a(x):
...    print(x)

>>>mylist = list(range(10))
>>> a(mylist.append(1))
None

>>> a(mylist + [5])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 5]

【讨论】:

  • 我完全忘记了它是一个方法并且会返回一个值。现在它是有道理的。现在回想起来很明显。谢谢@Alexander Huszagh。
  • 当然,如果我帮助了您并且回答了您的问题,并且您觉得没有更好的答案,请随时接受它作为答案。很高兴能提供帮助。
  • 如何接受答案。由于分数很少,我无法投票。有没有其他方法可以接受答案。
  • 看看这是否有帮助:meta.stackexchange.com/questions/23138/…
猜你喜欢
  • 1970-01-01
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 2018-06-06
  • 2014-10-03
  • 2016-03-10
相关资源
最近更新 更多