排列组合问题主要有4类:
1、笛卡尔积:
itertools.product(*iterables[, repeat])
2、排列:
itertools.permutations(iterable[, r])
3、组合:
itertools.combinations(iterable, r)
4、组合(包含自身重复):
itertools.combinations_with_replacement(iterable, r)
笛卡尔积:若是单一列表笛卡尔乘积,则包含本身。例子中的AA,BB,CC
import itertools
for i in itertools.product('ABC', repeat=2):
print(''.join(i), end=" ")
print('\n') # 输出 AA AB AC BA BB BC CA CB CC
# 两个元组进行笛卡尔积:
a = (1, 2)
b = ('A', 'B', 'C')
c = itertools.product(a, b)
for i in c:
print(i, end=",")
# 输出(1, 'A') (1, 'B') (1, 'C') (2, 'A') (2, 'B') (2, 'C')
排列:
import itertools
for i in itertools.permutations('ABC', 2):
print(''.join(i), end=" ")
# 输出 AB AC BA BC CA CB
print('\n')
# 全排列:实际场景比较普遍。
# 例如:力扣题 - 没有重复元素集合的全排列:
# https://leetcode-cn.com/problems/VvJkup/
data = "ABC"
for i in itertools.permutations(data, len(data)):
print(''.join(i), end=" ")
# ABC ACB BAC BCA CAB CBA
print('\n')
组合:
import itertools
for i in itertools.combinations('ABC', 1):
print(''.join(i), end=" ")
# 输出 A B C
print('\n')
for i in itertools.combinations('ABC', 2):
print(''.join(i), end=" ")
# 输出 AB AC BC
print('\n')
for i in itertools.combinations('ABC', 3):
print(''.join(i), end=" ")
# 输出 ABC
print('\n')
组合(包含自身重复):
import itertools
for i in itertools.combinations_with_replacement('ABC', 1):
print(''.join(i), end=' ')
# 输出 A B C
print('\n')
for i in itertools.combinations_with_replacement('ABC', 2):
print(''.join(i), end=' ')
# 输出 AA AB AC BB BC CC
print('\n')
for i in itertools.combinations_with_replacement('ABC', 3):
print(''.join(i), end=' ')
# 输出 AAA AAB AAC ABB ABC ACC BBB BBC BCC CCC
print('\n')
# 子集:
nums = [1, 2, 3]
new_list = [[], nums]
for i in range(1, len(nums) + 1):
for j in itertools.combinations(nums, i):
new_list.append(list(j))
print(new_list)
# [[], [1, 2, 3], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
举例:
'BCDEF五个字母组合问题'
import itertools
print("1个组合:")
for i, val in enumerate(list(itertools.combinations('BCDEF', 1))):
print("序号:%s 值:%s" % (i + 1, ''.join(val)))
print("2个组合:")
for i, val in enumerate(list(itertools.combinations('BCDEF', 2))):
print("序号:%s 值:%s" % (i + 1, ''.join(val)))
print("3个组合:")
for i, val in enumerate(list(itertools.combinations('BCDEF', 3))):
print("序号:%s 值:%s" % (i + 1, ''.join(val)))
print("4个组合:")
for i, val in enumerate(list(itertools.combinations('BCDEF', 4))):
print("序号:%s 值:%s" % (i + 1, ''.join(val)))
print("5个组合:")
for i, val in enumerate(list(itertools.combinations('BCDEF', 5))):
print("序号:%s 值:%s" % (i + 1, ''.join(val)))
微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!