计数变量在递归函数中没有更新

2024-03-28 11:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码正在查找置换,但是count变量没有更新。谁能指出这个错误,为什么count中的变化没有反映出来。在

def swap_arr_elems(arr, src_idx, dest_idx):
    tmp = arr[src_idx]
    arr[src_idx] = arr[dest_idx]
    arr[dest_idx] = tmp
    return

def permuate(arr, left, right, output, count):
    if left == right:
        output.append(list(arr))
        count += 1
        #count.append('1')
        return

    for i in range(left, right, 1):
        swap_arr_elems(arr, left, i)
        permuate(arr, left + 1, right, output, count)
        swap_arr_elems(arr, left, i)


if __name__ == '__main__':
    count = 0    
    #count = []
    test_input = ['a', 'b', 'c']
    test_output = []
    permuate(test_input, 0, len(test_input), test_output, count)
    print("count : " + str(count))
    for item in test_output:
        print(item)

编辑1:

^{pr2}$

Tags: testrightsrcinputoutputdefcountleft
3条回答

是的,count变量的作用域只在主循环中。在

if main循环中的count变量与permuate函数中的计数变量不同。在

如果您想从permuate函数获得count变量的值,那么从函数返回count值并接受in count变量。在

演示:

>>> count = 10
>>> def test(count):
...    count += 1
...    print "In test:", id(count)
...    return count
... 
>>> count = test(count)
In test: 149784632
>>> count 
11

left==right时,您只增加count,然后从中返回,增加count不会在调用函数中自动增加,您可以尝试返回该计数,然后在调用它的函数中接受它。在

示例-

def permuate(arr, left, right, output, count):
    if left == right:
        output.append(list(arr))
        count += 1
        #count.append('1')
        return count

    for i in range(left, right, 1):
        swap_arr_elems(arr, left, i)
        count += permuate(arr, left + 1, right, output, count)
        swap_arr_elems(arr, left, i)
    return count

if __name__ == '__main__':
    count = 0    
    #count = []
    test_input = ['a', 'b', 'c']
    test_output = []
    count = permuate(test_input, 0, len(test_input), test_output, count)
    print("count : " + str(count))
    for item in test_output:
        print(item)

我个人把它命名为可变和非可变效应不知道它是真的

Count是一个整数。也就是说,它是一个不可变的对象,它的作用域在main函数内,所以它的值不会改变

也就是说,当您count+=1时,将创建一个新对象,而该对象不会返回

测试输出是一个列表。这个是一个可变对象。即使更改了它的值,它也会在同一个列表中更改

output.append(list(arr)) #adds to the same  test_output list

有关可变和非可变对象和行为的详细信息,请参阅link

根据@brunodesthuilliersoutput=output+list(arr)更改输出。这是由于+创建了一个新对象,请参见下面的解释

^{pr2}$

相关问题 更多 >