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