gpt4 book ai didi

python - 返回 list.append() 在递归函数中抛出 "TypeError: unsupported operand type(s)"

转载 作者:行者123 更新时间:2023-12-01 01:03:55 26 4
gpt4 key购买 nike

我尝试编写一个递归函数来返回最长的递增子序列,但出现错误,显示“TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

def helper(cur_seq, seq, cur_i, result):
if len(seq) == cur_i:
return result.append(cur_seq)
else:
next_i = cur_i + 1
if len(cur_seq) == 0 or seq[cur_i] > cur_seq[-1]:
temp = cur_seq.copy()
temp1 = cur_seq.copy()
temp.append(seq[cur_i])
return helper(temp, seq, next_i, result) + helper(temp1, seq, next_i, result)
else:
return helper(cur_seq.copy(), seq, next_i, result)


def longest_sub_sequence(seq):
cur_seq = []

result = helper(cur_seq, seq, 0, [])

max_length = 0
for i in result:
if len(i) > max_length:
max_length = len(i)


return max_length


if __name__ == "__main__":

seq = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
y = longest_sub_sequence(seq)
print(y)

最佳答案

list.append 是就地操作。例如,

l = [1, 2, 3]
result = l.append(4)

print(result)
# None

print(l)
# [1, 2, 3, 4]

append 返回 None,就地修改 l。这意味着函数中的 return result.append(cur_seq) 将返回 None,并且两个递归调用的结果是 None + None,这给出了你的TypeError

修复方法是追加,稍后返回。

def helper(cur_seq, seq, cur_i, result):
if len(seq) == cur_i:
result.append(cur_seq)
return result
...

关于python - 返回 list.append() 在递归函数中抛出 "TypeError: unsupported operand type(s)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557384/

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