Python – get all possible sums of elements inside n 1d arrays

  • A+
Category:Languages

Given an integer n, and an array a, I would like to return an array with all the possible values of sums of a with itself n times.

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] 

First element is from 1+1+1, second is 1+1+2 etc.

Is there any elegant way to do that? I've tried loops, but since n isn't known in advance, I don't know how many loops I need to make.

Thanks in advance

 


Generate all possible 3-element combinations, then sum them:

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] 

Since you seem to be interested in the unique sums, use a set:

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} 

Note that there is no guarantee whatsoever that these will be ordered. If you want ordered output be explicit about it:

print(sorted(set(sum(comb) for comb in combinations_with_replacement(li, n)))) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: