我想比较python中两个递归函数中变量之间的差异。第一个是:def helper(nums, target, count): print(count) if target < 0: return elif target == 0: count += 1 else: for i in range(0, len(nums)): helper(nums, target-nums[i], count)count = 0helper([1, 2, 3], 4, count)计数变量始终为 0。第二个是:def helper(nums, target, path, res): print(res) if target < 0: return elif target == 0: res.append(path) else: for i in range(0, len(nums)): helper(nums, target-nums[i], path + [nums[i]], res)path = []res = []helper([1, 2, 3], 4, path, res)资源会不断变化。谁能告诉我为什么 count 变量总是等于 0?python中递归函数中的整数变量和列表变量有区别吗?
1 回答

眼眸繁星
TA贡献1873条经验 获得超9个赞
第一个helper
,count
是一个局部变量。当助手返回时,特定调用中的任何更改都将丢失。也许你想global count
在帮手的顶部。
在第二个helper
,res
也是本地名称,而是将新对象重新绑定到本地名称,代码对列表对象进行了变异,并且新添加的不会消失。
添加回答
举报
0/150
提交
取消