Stefan Porojanu
Stefan Porojanu

Reputation: 21

Is there a function for finding which floats in list add up to a number in a specific interval?

I have a specific list with up to 6 float numbers and I need a function to choose which of these 6 numbers when added up result in a number in a given interval for example: 29 < Sum < 31.

list = [0.96, 6.72, 4.8, 7.68, 24.96, 6.72]
min_number = 29
max_number = 31

If it is possible I would also like to be able to move the resulting floats to a new list, and the rest to another list.

Upvotes: 2

Views: 92

Answers (1)

Paolo
Paolo

Reputation: 26220

A possible solution is to generate all the n length combinations of the list, where:

1 < n < len(list)


The following code:

import itertools

mylist = [0.96, 6.72, 4.8, 7.68, 24.96, 6.72]
min_number = 29
max_number = 31

all_perms = []

for index in range(len(mylist)):
    perm = itertools.combinations(mylist,index)
    for i in perm:
        all_perms.append(i)

for i in all_perms:
    if min_number < sum(i) < max_number:
        print(i)

Prints the unique combinations:

(4.8, 24.96)
(0.96, 4.8, 24.96)

Upvotes: 2

Related Questions