类型错误:解包元组递归函数调用
我有以下代码:
def myCalculation(self, root, max_val):
if root == None:
return -1
LH = 1 + (self.myCalculation(root.left, max_val))[0]
RH = 1 + (self.myCalculation(root.right, max_val))[0]
ret = LH+RH
if max_val < ret:
max_val = ret
return (max(LH, RH), max_val)
在这里,我返回两个值,因为对于堆栈上的最后一个函数调用以退出函数,必须将max_val返回到调用函数。因此,当函数的第三和第4个可执行行中,我进行函数调用并尝试使用返回值时,它给出了下方的typeerror。
错误是:
> TypeError: 'int' object has no attribute '__getitem__'
完整的追溯:
TypeError: 'int' object has no attribute '__getitem__'
LH = 1 + (self.myCalculation(root.left, max_val))[0]
Line 14 in myCalculation (Solution.py)
LH = 1 + (self.myCalculation(root.left, max_val))[0]
Line 14 in myCalculation (Solution.py)
LH, max_val1 = 1 + self.myCalculation(root.left, 0)
Line 32 in diameterOfBinaryTree (Solution.py)
ret = Solution().diameterOfBinaryTree(param_1)
Line 67 in _driver (Solution.py)
_driver()
第77行(solution.py)
我无法弄清楚递归中包装和解开包装的问题是什么?
I have the following piece of code:
def myCalculation(self, root, max_val):
if root == None:
return -1
LH = 1 + (self.myCalculation(root.left, max_val))[0]
RH = 1 + (self.myCalculation(root.right, max_val))[0]
ret = LH+RH
if max_val < ret:
max_val = ret
return (max(LH, RH), max_val)
Here, I return two values because for the last function call on stack to exit the function must return the max_val to the calling function. So, when at the 3rd and 4th executable lines of the function I make a function call and try to use the return values, it gives TypeError desribed just below.
The error is :
> TypeError: 'int' object has no attribute '__getitem__'
Full traceback:
TypeError: 'int' object has no attribute '__getitem__'
LH = 1 + (self.myCalculation(root.left, max_val))[0]
Line 14 in myCalculation (Solution.py)
LH = 1 + (self.myCalculation(root.left, max_val))[0]
Line 14 in myCalculation (Solution.py)
LH, max_val1 = 1 + self.myCalculation(root.left, 0)
Line 32 in diameterOfBinaryTree (Solution.py)
ret = Solution().diameterOfBinaryTree(param_1)
Line 67 in _driver (Solution.py)
_driver()
Line 77 in (Solution.py)
I cannot quite figure what the problem is with packing and unpacking tuples in recursion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您的基本情况返回一个单个值。不过,您可以通过消除返回多个值和额外参数
max_val
的需要来简化算法。我们可以计算树的直径
,t
-其中树的
高度
,t
定义为-您可以在
Solution
类中编写myCalculation
-因为
height
将在子节点上被多次调用,所以可以使用lru_cache
,有效地“记忆”功能 -The issue is your base case returns a single value. However, you can simplify your algorithm by removing the need to return multiple values and the extra parameter,
max_val
. We can calculate thediameter
of a tree,t
-Where
height
of a tree,t
, is defined as -You can write
myCalculation
in yourSolution
class -Because
height
will be called multiple times on child nodes, this program can be optimized usinglru_cache
, effectively "memoizing" the function -