Python两种顺序生成组合
1、默认顺序说明
通过itertools.combinations可以生成组合,类似于深度搜索的顺序,对于C(6,3)按照如下顺序生成组合:
C(6,3)默认顺序组合:
(1, 2, 3)
(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(1, 5, 6)
(2, 3, 4)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)
(2, 5, 6)
(3, 4, 5)
(3, 4, 6)
(3, 5, 6)
(4, 5, 6)
2、增量生成组合的顺序说明
某些时候,需要优先使用排在前面的元素生成组合,穷尽之后,再加入新元素产生新的组合,对于C(6,3)顺序如下:
C(6,3)增量顺序组合:
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
(1, 2, 5)
(1, 3, 5)
(1, 4, 5)
(2, 3, 5)
(2, 4, 5)
(3, 4, 5)
(1, 2, 6)
(1, 3, 6)
(1, 4, 6)
(1, 5, 6)
(2, 3, 6)
(2, 4, 6)
(2, 5, 6)
(3, 4, 6)
(3, 5, 6)
(4, 5, 6)
3、两种顺序生成组合的参考Python代码
# coding=utf-8
from itertools import combinationsdef incremental_combinations(iterable, r):"""生成不重复的增量组合:每次只新增包含最新元素的组合"""pool = tuple(iterable)n = len(pool)if r > n or r < 1:return# 首先生成前r个元素的组合yield from combinations(pool[:r], r)# 逐步扩展范围,只生成包含新元素的组合for end in range(r + 1, n + 1):new_element = pool[end - 1]# 获取前end-1个元素中选r-1个的组合base_combos = combinations(pool[:end - 1], r - 1)# 将新元素与基础组合合并for base in base_combos:yield base + (new_element,)if __name__ == '__main__':data = [1,2,3,4,5,6]cmb_gen = combinations(data,3)print('C(6,3)默认顺序组合:')for cmb in cmb_gen:print(cmb)cmb_gen = incremental_combinations(data,3)print('C(6,3)增量顺序组合:')for cmb in cmb_gen:print(cmb)
4、组合的数量计算
import math
comb_size = math.comb(6,3) # python 3.8及以上