-1

我对 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

4

2 回答 2

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]
于 2013-03-11T06:10:12.713 回答
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)]
于 2013-03-11T06:31:36.520 回答