为了账号安全,请及时绑定邮箱和手机立即绑定

python中递归函数的不同变量

python中递归函数的不同变量

米脂 2021-06-03 13:25:47
我想比较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也是本地名称,而是将新对象重新绑定到本地名称,代码对列表对象进行了变异,并且新添加的不会消失。


查看完整回答
反对 回复 2021-06-08
  • 1 回答
  • 0 关注
  • 192 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号