python中递归函数的不同变量

我想比较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 = 0

helper([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中递归函数中的整数变量和列表变量有区别吗?


米脂
浏览 193回答 1
1回答

眼眸繁星

第一个helper,count是一个局部变量。当助手返回时,特定调用中的任何更改都将丢失。也许你想global count在帮手的顶部。在第二个helper,res也是本地名称,而是将新对象重新绑定到本地名称,代码对列表对象进行了变异,并且新添加的不会消失。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python