我有两个功能,prod
和perm
。它们非常相似。它们都使用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)
答案 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)