首页 > 解决方案 > 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,我不知道我需要制作多少个循环。

提前致谢

标签: python

解决方案


生成所有可能的 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))))

推荐阅读