具有意外结果的Python编号列表排列

时间:2012-06-04 02:16:09

标签: python list permutation

我试图获取包含0-9的数字列表并返回列表的所有排列。我已经提出了两个不同的函数,它们在一定程度上返回了预期的结果,但是,这两个函数都不是我的目标。这是一个返回一个周期的正确结果:

x = [0,1,2,3,4,5,6,7,8,9]

def test(x):
  place_holder = 9
  count = 9
  print x
  while count > 1:
    old_x = x[count]
    x[count] = x[count-1]
    x[count-1] = old_x
    count -= 1
    print x
    if count == 1:
      x.sort()
      place_holder -= 1
      count = place_holder

返回:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 9, 8]
[0, 1, 2, 3, 4, 5, 6, 9, 7, 8]
[0, 1, 2, 3, 4, 5, 9, 6, 7, 8]
[0, 1, 2, 3, 4, 9, 5, 6, 7, 8]
[0, 1, 2, 3, 9, 4, 5, 6, 7, 8]
[0, 1, 2, 9, 3, 4, 5, 6, 7, 8]
[0, 1, 9, 2, 3, 4, 5, 6, 7, 8]
[0, 9, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 8, 7, 9]
[0, 1, 2, 3, 4, 5, 8, 6, 7, 9]
[0, 1, 2, 3, 4, 8, 5, 6, 7, 9]
[0, 1, 2, 3, 8, 4, 5, 6, 7, 9]
[0, 1, 2, 8, 3, 4, 5, 6, 7, 9]
[0, 1, 8, 2, 3, 4, 5, 6, 7, 9]
[0, 8, 1, 2, 3, 4, 5, 6, 7, 9]
[0, 1, 2, 3, 4, 5, 7, 6, 8, 9]
[0, 1, 2, 3, 4, 7, 5, 6, 8, 9]
[0, 1, 2, 3, 7, 4, 5, 6, 8, 9]
[0, 1, 2, 7, 3, 4, 5, 6, 8, 9]
[0, 1, 7, 2, 3, 4, 5, 6, 8, 9]
[0, 7, 1, 2, 3, 4, 5, 6, 8, 9]
[0, 1, 2, 3, 4, 6, 5, 7, 8, 9]
[0, 1, 2, 3, 6, 4, 5, 7, 8, 9]
[0, 1, 2,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, 5, 6, 8, 9]
[0, 1, 2, 7, 3, 4, 5, 6, 8, 9]
[0, 1, 7, 2, 3, 4, 5, 6, 8, 9]
[0, 7, 1, 2, 3, 4, 5, 6, 8, 9]
[0, 1, 2, 3, 4, 6, 5, 7, 8, 9]
[0, 1, 2, 3, 6, 4, 5, 7, 8, 9]
[0, 1, 2, 6, 3, 4, 5, 7, 8, 9]
[0, 1, 6, 2, 3, 4, 5, 7, 8, 9]
[0, 6, 1, 2, 3, 4, 5, 7, 8, 9]
[0, 1, 2, 3, 5, 4, 6, 7, 8, 9]
[0, 1, 2, 5, 3, 4, 6, 7, 8, 9]
[0, 1, 5, 2, 3, 4, 6, 7, 8, 9]
[0, 5, 1, 2, 3, 4, 6, 7, 8, 9]
[0, 1, 2, 4, 3, 5, 6, 7, 8, 9]
[0, 1, 4, 2, 3, 5, 6, 7, 8, 9]
[0, 4, 1, 2, 3, 5, 6, 7, 8, 9]
[0, 1, 3, 2, 4, 5, 6, 7, 8, 9]
[0, 3, 1, 2, 4, 5, 6, 7, 8, 9]
[0, 2, 1, 3, 4, 5, 6, 7, 8, 9]

正确地经历九个循环然后返回到0-9。所以我可以看到这是因为x.sort()调用。所以我把这个功能更改为:

def exp_test(x):
  static = []
  for i in x:
    static.append(i)
  place_holder = 9
  count = 9
  print x
  while count > 1:
    old_x = x[count]
    x[count] = x[count-1]
    x[count-1] = old_x
    count -= 1
    print x
    if count == 1:
      x = static
      place_holder -= 1
      count = place_holder

现在这个工作正常,直到七个班次转移到每一个数字。我认为计数混乱了,但是,我经历了,没有看到它?

2 个答案:

答案 0 :(得分:3)

尝试将x = static语句中的if修改为x = static[:]。问题是您只需将名称x重新绑定到static绑定的同一列表。你真的想要复制static所绑定的内容。

答案 1 :(得分:2)

最好的解决方案是

from itertools import permutations

但如果您必须自己编写,通常的解决方案是递归的:

def permutations(seq):
    _len = len(seq)
    if _len:
        if _len==1:
            yield seq
        else:
            for p in permutations(seq[1:]):
                for i in range(_len):
                    yield p[:i] + seq[0:1] + p[i:]

编辑:好吧,欧拉问题需要一个完全不同的方法......诀窍不是产生高达1,000,000的所有排列(这将太慢),而是要计算什么百万分之一的排列必须是。有n!排列n项的方法 - 你可以在序列的尾部递归地使用它来计算出必须重新安排多少个子序列以达到百万分之一的安排,并从中找出必须安排的内容。

你需要写一些更像

的东西
def nth_arrangement(seq, n):
    # you have to figure this bit out!