0

I have a python list, similar to the following:

foo = [1, 2, 3, 4, 5]

I'd like to find a way to sum some of the list elements, provided the sum does not exceed a specific value, such as "7" in the list above. I want it to find all the combinations that do not exceed "7".

I need it to return a result that looks something like:

[1, 2, 3]
[1, 4]
[2, 4]
[1, 5]

I'm aware I can already sum a complete list using sum(foo), but I only want to sum part of the list. I'm not aware of a way to introduce an if sum(foo) < 7 argument that only sums some of the terms.

How would I do this? Should I be using itertools.combinations?

Alligator
  • 691
  • 3
  • 11
  • 21
  • Question for you: does the number of digits to sum have to be at least 2? – rahlf23 Nov 22 '17 at 23:22
  • Yes, the number of digits needs to be at least two. It does look like this is a duplicate question. Here is the previous answer, which is very similar. https://stackoverflow.com/questions/46942681/how-to-find-all-combinations-that-sum-up-to-at-most-a-constant – Alligator Nov 22 '17 at 23:24
  • 1
    Well since I can't answer this one explicitly, this should get you started (apologies ahead of time for the formatting in the comments): from itertools import combinations foo = [1, 2, 3, 4, 5] combos = [] for r in range(1,len(foo)): combos.append([','.join(map(str, comb)) for comb in combinations(foo, r) if sum(comb)<7]) – rahlf23 Nov 22 '17 at 23:25
  • Very elegant. Nice answer. I wish I could upvote it. This is why StackOverflow is frustrating. I tried to ask a valid question and I get downvotes. Makes me not want to use the site anymore. – Alligator Nov 22 '17 at 23:29
  • Shoot me an upvote on the comment and I'll be happy lol. Hope I got you started! And yes, sometimes it seems that people are quick to jump to a 'duplicate question' conclusion... – rahlf23 Nov 22 '17 at 23:30
  • Didn't know I could upvote a comment. Done. – Alligator Nov 22 '17 at 23:45

0 Answers0