非递归版本排列

时间:2013-10-19 12:06:08

标签: python recursion combinations permutation

我有两个功能,prodperm。它们非常相似。它们都使用recursive。现在我不想用for循环替换递归。 prod2工作正确,但perm2没有,我该如何解决?

#Recursive version:

def prod(A,k):
    return [[]] if k==0 else [[a]+b for a in A for b in prod(A,k-1)]

def perm(A,k):
    return [[]] if k==0 else [[a]+b for a in A for b in perm([i for i in A if i!=a],k-1)]


#NonRecursive version:

def prod2(A,k):
    r=[[]]
    for i in range(k):
        r=[[a]+b for a in A for b in r]
    return r

def perm2(A,k):
    r=[[]]
    for i in range(k):
        r=[[a]+b for a in A for b in [i for i in r if i!=a ] ]
    return r

print prod([1,2,3],2)
print prod2([1,2,3],2)

print perm([1,2,3],2)
print perm2([1,2,3],2)

2 个答案:

答案 0 :(得分:3)

由于代码中的r变量包含列表,i != a始终为True。以下是如何解决它:

def perm2(A, k):
    r = [[]]
    for i in range(k):
        r = [[a] + b for a in A for b in [i for i in r if a not in i]]
    return r

或者简单地说:

def perm2(A, k):
    r = [[]]
    for i in range(k):
        r = [[a] + b for a in A for b in r if a not in b]
    return r

答案 1 :(得分:1)

漂亮的解决方案专家,这是与Numba一起使用的重写:

@numba.njit()
def permutations(A, k):
    r = [[i for i in range(0)]]
    for i in range(k):
        r = [[a] + b for a in A for b in r if (a in b)==False]
    return r
permutations([1,2,3],3)