0

Given a list, how can I find sums of part of the list? For example:

a = [2,5,4,6,8]
sum(a) = 25

I want to find out if a part of the list sums up to a certain number.
The list part should have a certain length. This is my goal:

ex_list = [2,5,4,6,8]
dif_list = partsum(ex_list, 3)
print(dif_list) ==> [11, 13, 15, 12, 14, 16, 15, 17, 19, 18]

Each element in 'dif_list' is given by taking 3 numbers out of 'ex_list' and summing them up, i.e. 2+5+4 = 11, 2+5+6 = 13, 2+5+8 = 15, 2+4+6 = 12, etc.
Also for reference:

ex_list = [2,5,4,6,8]
another_list = partsum(ex_list, 4)
print(another_list) ==> [17, 19, 21, 20, 23]

Because 2+5+4+6 = 17, 2+5+4+8 = 19, etc.
Basically, partsum(thing, num) will take 'num' items of 'thing', sum them up, and append it to a new list. All help is appreciated, thanks!

4
  • 1
    What's the larger context you need this for? Commented Dec 30, 2017 at 20:47
  • So you want all combinations with num elements and their sum? Commented Dec 30, 2017 at 20:50
  • If you are trying to find partitions, using combinations is the least efficient way. Commented Dec 30, 2017 at 20:53
  • Are all of the numbers positive? Commented Dec 30, 2017 at 21:06

1 Answer 1

3

You want itertools.combinations.

import itertools

lst = [2,5,4,6,8]
combos = itertools.combinations(lst, 3)
# combos is equivalent to
# [ [2, 5, 4], [2, 5, 6], [2, 5, 8],
#   [2, 4, 6], [2, 4, 8], [2, 6, 8],
#   [5, 4, 6], [5, 4, 8], [5, 6, 8],
#   [4, 6, 8] ]
result = [sum(combo) for combo in combos]
Sign up to request clarification or add additional context in comments.

8 Comments

and if you want to only have distinct sums change the last line into set([sum(combo) for combo in combos])
@hansaplast Why not a set comprehension?
@AdamSmith Thanks! And will this work if there are less than 3 items in a list 'lst' for combinations(lst,3)? (Or I can find out eventually...)
@adamsmith The program I'm using can't import itertools
@ChristopherMarley that's fine, write your own version then. I'm not sure why you wouldn't be able to import it though, it's part of the stdlib LOL!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.