# How do I calculate a sum of individual values that fit in a range using the least amount of datums

## Question:

I am trying to calculate a way to find a sum of numbers that fit into a range using the least amount of data and reach as close to the upper limit as possible. The upper limit receives priority.

```
individualValues = {0.07, 0.1, 0.15, 0.25, 0.33, 0.45, 0.6 , 1.2}
lowerLimit = 0.8
UpperLimit = 1
```

A good result to this question would be one as close to the upper limit as possible using the least amount of values. I.E

answer = {0.07, 0.6, 0.33}

## Answers:

Do the values need to be in a set? If not you can put them in a list and then do a for loop to pull values greater than .8 and less than 1 and put them in a new value list

There’s probably a far superior mathematical approach but this seems to work:

```
from itertools import combinations
values = [0.07, 0.1, 0.15, 0.25, 0.33, 0.45, 0.6 , 1.2]
lowerLimit = 0.8
UpperLimit = 1.0
result = None
for m in range(len(values), 0, -1):
for combo in combinations(values, m):
if lowerLimit <= (sc := sum(combo)) <= UpperLimit:
if result is None or (sc > sr and len(result) > m):
result = combo
sr = sc
print(result)
```

**Output:**

```
(0.07, 0.33, 0.6)
```