排列代码不能完全按照我的意愿去做

时间:2013-03-11 06:05:26

标签: python permutation combinations

我是python的新手,我已经完成了这个代码,而不是我想做的事情。 很感激帮助。

这是我到目前为止的代码

def permute(LIST):

    length=len(LIST)
    if length <= 1:
        yield LIST
    else:
        for n in range(0,length):
             for end in permute( LIST[:n] + LIST[n+1:] ):
                 yield [ LIST[n] ] + end

当我给它类似[4,3,2,1]的东西时,它不重复最后一个数字,它只是 为每个字母组合一次。因此输出永远不会是[4,3,2,2]。

但我希望它能做到这一点。这是我想要输出的例子

INPUT = ['1','2','3','4']

OUTPUTs = [1 2 3 4][1 2 3 1][1 2 3 2][1 2 3 3] [1 2 4 1][1 2 4 2] [1 2 4 3] [1 2 4 4] [1 2 1 1]and so on

如何对我的代码实施此更改?

谢谢你的帮助

编辑:我不能使用ITERTOOLS

2 个答案:

答案 0 :(得分:1)

行。我使用itertools.permutations得到-1 :(

似乎你需要重复排列而不使用itertools。 你走了:

def permutation_with_repitition(items, prefix):
  if len(prefix) == len(items):
     yield prefix

  else:
    for item in items:
      prefix.append(item)
      for p in  permutation_with_repitition(items, prefix):
        yield p
      prefix.pop()

L = [1,2,3]

for p in permutation_with_repitition(L, []):
  print p

输出:

[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 1]
[1, 2, 2]
[1, 2, 3]
[1, 3, 1]
[1, 3, 2]
[1, 3, 3]
[2, 1, 1]
[2, 1, 2]
[2, 1, 3]
[2, 2, 1]
[2, 2, 2]
[2, 2, 3]
[2, 3, 1]
[2, 3, 2]
[2, 3, 3]
[3, 1, 1]
[3, 1, 2]
[3, 1, 3]
[3, 2, 1]
[3, 2, 2]
[3, 2, 3]
[3, 3, 1]
[3, 3, 2]
[3, 3, 3]

答案 1 :(得分:0)

但也许itertools.product就是你想要的:

>>> I = range(3)
>>> print list(itertools.product(I, repeat=len(I)))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]