2013-03-11 50 views
-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

+1

恐怕你想要的不是pe rmutation。 – waitingkuo 2013-03-11 06:21:43

+0

无论如何检查我的答案.. – zzk 2013-03-11 06:46:05

回答

1

确定。我-1使用和itertools.permutations :(

好像你需要重复排列,而无需使用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] 
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)] 
相关问题