使用 Python 查找总结数据集的唯一组合
Finding unique combination that sums up the dataset using Python
我从某个地方得到这个问题作为数据工程测试的练习。
给定一组候选数字 (C) 和一个目标数字 (T),找出 C 中候选数字总和为 T 的所有唯一组合。
要求:
C中每个数字只能组合使用一次。
C和T永远是正整数
Example: find a target = 6 from a dataset of [3,5,6,1,2]. the solution is
- [3,1,2]
- [5,1]
- [6]
我只知道这是一个Apriori算法,但我不知道如何解决这个问题。
使用 itertools.combinations
查找列表中每种可能尺寸的独特组合。例如
from itertools import combinations
a = [3,5,6,1,2]
target = 6
result = []
for i in range(1,len(a)+1):
combs = combinations(a, i)
for c in combs:
if sum(c) == target:
result.append(list(c))
print(result) # Output [[6], [5, 1], [3, 1, 2]]
我从某个地方得到这个问题作为数据工程测试的练习。
给定一组候选数字 (C) 和一个目标数字 (T),找出 C 中候选数字总和为 T 的所有唯一组合。
要求: C中每个数字只能组合使用一次。 C和T永远是正整数
Example: find a target = 6 from a dataset of [3,5,6,1,2]. the solution is
- [3,1,2]
- [5,1]
- [6]
我只知道这是一个Apriori算法,但我不知道如何解决这个问题。
使用 itertools.combinations
查找列表中每种可能尺寸的独特组合。例如
from itertools import combinations
a = [3,5,6,1,2]
target = 6
result = []
for i in range(1,len(a)+1):
combs = combinations(a, i)
for c in combs:
if sum(c) == target:
result.append(list(c))
print(result) # Output [[6], [5, 1], [3, 1, 2]]