【发布时间】:2014-04-15 21:45:20
【问题描述】:
我编写了一个脚本来查找按字典顺序排列的数字列表的所有排列。立即打印时输出是正确的,但是如果我将其附加到列表中,它会发生变化。在我的脚本的输出中,首先您会看到包含单个元素的列表,然后是我附加到该元素的列表,最后您会看到添加子列表后的完成列表:
Find all permutations of 1 -> x. x = ? 3
[[1, 2, 3]]
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 3, 2], [2, 3, 1], [2, 3, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
如您所见,最初的 [1, 2, 3] 列表甚至不在最终输出中。下面是我的代码。谁能告诉我这是怎么回事?
permutation_range = int(input('Find all permutations of 1 -> x. x = ? '))
def permutation_finder(x):
permutation = list(range(1, 1+x))
rev_permutation = permutation[::-1]
permutation_list = [permutation]
print(permutation_list, '\n\n') #bugcheck print
while permutation != rev_permutation:
permutation, index_k = step_1(permutation)
permutation, index_k, index_l = step_2(permutation, index_k)
permutation, index_k = step_3(permutation, index_k, index_l)
permutation = step_4(permutation, index_k)
permutation_list.append(permutation)
print(permutation) #bugcheck print
return permutation_list
def step_1(permutation):
for val in permutation[:-1][::-1]:
index_k = permutation.index(val)
if val < permutation[index_k+1]:
return permutation, index_k
def step_2(permutation, index_k):
for val in permutation[index_k+1:][::-1]:
if val > permutation[index_k]:
index_l = permutation.index(val)
return permutation, index_k, index_l
def step_3(permutation, index_k, index_l):
a_k, a_l = permutation[index_k], permutation[index_l]
permutation[index_k], permutation[index_l] = a_l, a_k
return permutation, index_k
def step_4(permutation, index_k):
front = permutation[:index_k+1]
back = permutation[index_k+1:]
back.reverse()
permutation = front + back
return permutation
print('\n\n', permutation_finder(permutation_range))
【问题讨论】:
-
顺便说一句,我在
[[1, 2, 3]]之后和最终列表之前只打印了 5 个列表 -
你知道吗? Python 已经有一个
permutations方法。 (我并不是说自己编写是没有意义的——这当然是一种教育体验 :-)) -
是的,当我弄清楚我想问什么的时候,我一直在乱搞。它使我在问题中的输出不“非常”准确。对不起!
-
是的,我知道 Python 有自己的方法。我正在尝试手动解决许多问题,以便将它们设置在我的脑海中!
标签: python list python-3.4