置换码并不是我想要的那样

2024-04-29 19:56:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 代码inforlenifdefrange数字
2条回答

但也许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)]

好的。我用了-1itertools.排列:(

似乎你需要不使用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]

相关问题 更多 >