又改成可以同时对应排列,组合的(组合就是每次取得必须是大于之前的,排列就是每次都从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] |