python - 给定一个数字列表,如何创建总和的所有组合并返回这些总和的列表
问题描述
让我们假设我们有一个数字列表 [1,2,3],我们必须将所有可能的元素总和组合附加到一个数组中并返回该数组?
如何获得以下金额
1 = 1 (the first element so simply add it to the ans array)
1 + 2 = 3
1 + 3 = 4
1 + 2 + 3 = 6
1 + 3 + 2 = 6
2 = 2 (second element so simply add it to ans array)
2 + 1 = 3
2 + 3 = 5
2 + 1 + 3 = 6
2 + 3 + 1 = 6
3 + 1 = 4
3 = 3 (third element so simply add it to ans array)
3 + 1 = 4
3 + 2 = 5
3 + 1 + 2 = 6
3 + 2 + 1 = 6
所以我们的最终数组看起来像 [1,3,4,6,6,2,3,5,6,6,3,4,5,6,6]
解决方案
使用itertools
:
import itertools
nums = [1,2,3]
results = []
def split(a, n):
k, m = divmod(len(a), n)
return [a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n)]
for i in range(len(nums)):
results.append(split(list(map(sum,itertools.permutations(nums,i+1))),len(nums)))
results = zip(*results)
results = list(itertools.chain.from_iterable(itertools.chain.from_iterable(results)))
print(results)
>>> [1, 3, 4, 6, 6, 2, 3, 5, 6, 6, 3, 4, 5, 6, 6]
推荐阅读
- c++ - 枚举类比较不是默认值
- php - 为什么使用 SQL AVG() 函数时 mysqli_num_rows 总是返回 1?
- php - 如何从数据库中打开多个下拉列表。如何为每个获取的下拉按钮分配唯一 ID
- html - 手机优先。媒体查询不适用于特定 div
- c - C - wcstok() 错误结果
- java - Tomcat/SQL Server/Spring - 当 JNDI 配置导致 setStructured 参数时,使用 SQLServerCallableStatement 进行投射异常
- c - 不明白为什么每次输入相同的字母“ch”时wincounter不增加
- php - Msql:无法连接:无效设置。配置中定义的 controluser 连接失败
- android - Android 开源项目 (AOSP) 是否已经在 android SDK 中
- css - CSS - 带有图像的简单动画