gpt4 book ai didi

Python:帮助改进递归函数

转载 作者:行者123 更新时间:2023-12-01 04:56:19 36 4
gpt4 key购买 nike

我有以下函数,它有时会返回错误“全局名称'x'未定义”,当它跳转到return语句时会发生这种情况。我希望帮助改进此代码而不丢失功能。任何见解将不胜感激。

 def label(tree, instance, class_labels):
'''Returns the label at the end of every "branch" in the tree'''
global x
for row in tree:
if row[0] == instance[row[1]]:
if row[2][0] in class_labels:
x = row[2][0]
return x
else:
x = label(row[2], instance, class_labels)
return x

最佳答案

这可能有帮助...

def label(tree, instance, class_labels):
'''Returns the label at the end of every "branch" in the tree'''
last = None
for row in tree:
if row[0] == instance[row[1]]:
if row[2][0] in class_labels:
return row[2][0]
next = label(row[2], instance, class_labels)
if next is not None:
last = next
return last

关于Python:帮助改进递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27264786/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com