【发布时间】:2015-09-27 09:57:46
【问题描述】:
以下代码正在查找排列,但 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:
output of the above code is:
count : 0
['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'b', 'a']
['c', 'a', 'b']
【问题讨论】:
-
一些想法:
permuate不是一个字;也许你的意思是permute?交换数组元素的更短(和more efficient)方法是使用arr[src_idx], arr[dest_idx] = arr[dest_idx], arr[src_idx]。最后,您可以通过使用yield list(arr)而不是output.append(list(arr))来避免使用output列表。 -
@Frerich Raabe 我是 python 的初学者,将尝试理解和使用 yield。感谢您指出这一点.. :)
标签: python