手工python怎么写全排列?

手工python怎么写全排列?

不用iteraltools的permutation

symbol=["A","B","C"]

rst=[]

for i in symbol:

for j in symbol:

for k in symbol:

rst.append([i,j,k])

print(rst)#生成排列

如果有N=10层,就很难写10个for循环了。应该怎样办呢?


回答:

可以考虑用递归啊,循环加递归即可。
比如:

python">rst=[]

symbol=["A","B","C","D","E","F","G","H","I","J"]

def perm(n,b,e):

if b>=e :

rst.append(n)

else:

i = b

for num in range(b, e):

n[num],n[i] = n[i],n[num]

perm(n,b+1,e)

n[num],n[i]=n[i],n[num]

perm(symbol, 0, len(symbol) )

print(rst)

以上是 手工python怎么写全排列? 的全部内容, 来源链接: utcz.com/p/938366.html

回到顶部