python 排列组合算法_python排列组合算法

其实和八皇后的算法差不多,八皇后不检查斜线的结果就是全排列,此外八皇后中检查皇后位置麻烦,这里只要把列表转成词典,检查一下长度就行了(有重复元素,比如到第二层,应该是1,2,如果是1,1,那么词典长度就只有1了,需要排除)

组合就是每次取得必须是大于之前的,排列就是每次都从0开始选:

def combination(n,c,com=1,limit=0,per=[]):

for pos in range(limit,n):

t = per + [pos]

if len(set(t)) == len(t):

if len(t) == c:

yield [pos,]

else:

for result in combination(n,c,com,com*pos, per + [pos,]):

yield [pos,] + result

print("排列:")

for res in combination(5,3,0):

print(res)

print("组合:")

for res in combination(5,3):

print(res)

结果:

排列:

[0, 1, 2]

[0, 1, 3]

[0, 1, 4]

[0, 2, 1]

[0, 2, 3]

[0, 2, 4]

[0, 3, 1]

[0, 3, 2]

[0, 3, 4]

[0, 4, 1]

[0, 4, 2]

[0, 4, 3]

[1, 0, 2]

[1, 0, 3]

[1, 0, 4]

[1, 2, 0]

[1, 2, 3]

[1, 2, 4]

[1, 3, 0]

[1, 3, 2]

[1, 3, 4]

[1, 4, 0]

[1, 4, 2]

[1, 4, 3]

[2, 0, 1]

[2, 0, 3]

[2, 0, 4]

[2, 1, 0]

[2, 1, 3]

[2, 1, 4]

[2, 3, 0]

[2, 3, 1]

[2, 3, 4]

[2, 4, 0]

[2, 4, 1]

[2, 4, 3]

[3, 0, 1]

[3, 0, 2]

[3, 0, 4]

[3, 1, 0]

[3, 1, 2]

[3, 1, 4]

[3, 2, 0]

[3, 2, 1]

[3, 2, 4]

[3, 4, 0]

[3, 4, 1]

[3, 4, 2]

[4, 0, 1]

[4, 0, 2]

[4, 0, 3]

[4, 1, 0]

[4, 1, 2]

[4, 1, 3]

[4, 2, 0]

[4, 2, 1]

[4, 2, 3]

[4, 3, 0]

[4, 3, 1]

[4, 3, 2]

组合:

[0, 1, 2]

[0, 1, 3]

[0, 1, 4]

[0, 2, 3]

[0, 2, 4]

[0, 3, 4]

[1, 2, 3]

[1, 2, 4]

[1, 3, 4]

[2, 3, 4]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值