Home > Software design >  Creating a list of 1-4 numbers that add to an x number according to a list
Creating a list of 1-4 numbers that add to an x number according to a list

Time:04-05

I still haven't gotten anywhere with this however, All I want to do is create a list of numbers according to a list of numbers that I'm getting from an API that adds up to a certain X number for example.

It shouldn't include duplicates and it has to be 1 - 4 numbers.

Premade list:

[200, 500, 700, 199, 200, 54543, 432]

Let's say I would like to create a list of numbers that add up to 1500 or less It should return

[700, 500, 200]

CodePudding user response:

A straightforward (unoptimized) approach is to generate all the possible combinations c and then filter for the ones with sum(c) <= 1500:

>>> premade_list = [200, 500, 700, 199, 200, 54543, 432]
>>> import itertools
>>> [list(c) for n in range(1, 5) for c in itertools.combinations(premade_list, n) if sum(c) <= 1500]
[[200], [500], [700], [199], [200], [432], [200, 500], [200, 700], [200, 199], [200, 200], [200, 432], [500, 700], [500, 199], [500, 200], [500, 432], [700, 199], [700, 200], [700, 432], [199, 200], [199, 432], [200, 432], [200, 500, 700], [200, 500, 199], [200, 500, 200], [200, 500, 432], [200, 700, 199], [200, 700, 200], [200, 700, 432], [200, 199, 200], [200, 199, 432], [200, 200, 432], [500, 700, 199], [500, 700, 200], [500, 199, 200], [500, 199, 432], [500, 200, 432], [700, 199, 200], [700, 199, 432], [700, 200, 432], [199, 200, 432], [200, 500, 199, 200], [200, 500, 199, 432], [200, 500, 200, 432], [200, 700, 199, 200], [200, 199, 200, 432], [500, 199, 200, 432]]

If you're specifically trying to find the single item that's closest to 1500, you can then take the min of the difference:

>>> list(min((
...     c for n in range(1, 5)
...     for c in itertools.combinations(premade_list, n)
...     if sum(c) <= 1500
... ), key=lambda c: 1500 - sum(c)))
[200, 500, 700]
  • Related