python - Python - 获取n个一维数组中所有可能的元素总和
问题描述
给定一个整数 n 和一个数组 a,我想返回一个数组,其中包含 a 与其自身 n 次之和的所有可能值。
Example: n = 3, a = [1, 2, 3, 4, 5, 6]
Output: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
第一个元素来自 1+1+1,第二个是 1+1+2 等等。
有什么优雅的方法可以做到这一点吗?我尝试过循环,但由于事先不知道 n,我不知道我需要制作多少个循环。
提前致谢
解决方案
生成所有可能的 3 元素组合,然后将它们相加:
from itertools import combinations_with_replacement
n = 3
li = [1, 2, 3, 4, 5, 6]
print([sum(comb) for comb in combinations_with_replacement(li, n)])
# [3, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 7, 8, 9, 10, 9, 10, 11, 11, 12, 13, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 12, 13, 14, 14, 15, 16, 15, 16, 17, 18]
由于您似乎对唯一总和感兴趣,请使用一组:
print(set(sum(comb) for comb in combinations_with_replacement(li, n)))
# {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
请注意,不保证会订购这些产品。如果您希望有序输出明确说明:
print(sorted(set(sum(comb) for comb in combinations_with_replacement(li, n))))
推荐阅读
- python - 如何使用漂亮的汤在数据框中附加数据
- php - 有没有办法使用亚马逊 MWS API 获取非活动产品?
- java - java.lang.NullPointerException: decodeResource(context.r…rces, R.drawable.ic_logo) 不能为空
- asp.net-core - 使用 HttpContext 时 Blazor 抛出错误
- c# - 根据.net核心中var中的条件插入对象列表/自定义模型列表
- ios - Child 如何使用 Screen Time API 在一段时间内取消阻止应用程序
- angular11 - 从表单设置日期值时,Angular ng2-datepicker 抛出无效时间
- stm32 - 外部 Flash Loader 链接器脚本文件
- java - 如何从活动中调用片段方法?
- azure - 如何在 azure devops pipline 中为 py 脚本调用 repo 路径