1

我有两个功能,prodperm。它们非常相似。它们都使用递归。现在我不想用 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)
4

2 回答 2

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
于 2013-10-19T13:38:19.363 回答
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)
于 2018-12-14T19:25:48.903 回答