下面的代码正在查找置换,但是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}$
是的,
count
变量的作用域只在主循环中。在if main
循环中的count
变量与permuate
函数中的计数变量不同。在如果您想从
permuate
函数获得count变量的值,那么从函数返回count值并接受in count变量。在演示:
当
left==right
时,您只增加count
,然后从中返回,增加count不会在调用函数中自动增加,您可以尝试返回该计数,然后在调用它的函数中接受它。在示例-
我个人把它命名为可变和非可变效应不知道它是真的
Count是一个整数。也就是说,它是一个不可变的对象,它的作用域在main函数内,所以它的值不会改变
也就是说,当您
count+=1
时,将创建一个新对象,而该对象不会返回测试输出是一个列表。这个是一个可变对象。即使更改了它的值,它也会在同一个列表中更改
有关可变和非可变对象和行为的详细信息,请参阅link
根据@brunodesthuilliers
^{pr2}$output=output+list(arr)
更改输出。这是由于+
创建了一个新对象,请参见下面的解释相关问题 更多 >
编程相关推荐