2

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.

Paolo
  • 21,270
  • 6
  • 38
  • 69
  • 1
    In addition to my answer, I would like to mention that you should **not** be using `list` as a name for a variable, since that is the name of a built in function in Python. – Paolo Sep 12 '19 at 16:40

1 Answers1

2

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)
Enlico
  • 23,259
  • 6
  • 48
  • 102
Paolo
  • 21,270
  • 6
  • 38
  • 69
  • Will it be possible to do this without converting the output to a list of strings? I would like them to retain their float properties. Thank you so much fur your answer – Stefan Porojanu Sep 13 '19 at 05:54
  • @StefanPorojanu I simplified the answer, let me know if that works for you. – Paolo Sep 14 '19 at 00:08
  • The problem that I have is that I need to be able to use the output so I need the combinations to be float numbers. – Stefan Porojanu Sep 16 '19 at 09:27
  • @StefanPorojanu Did you run the code? The output *is* a list of tuples of floats – Paolo Sep 16 '19 at 09:29
  • I did run it, but when I try to create a second list that contains the rest of the floats from mylist which are not in the output, bascially rest = mylist - i, I ran into trouble again: I am using rest= [x for x in mylistif x not in i] – Stefan Porojanu Sep 16 '19 at 09:33
  • @StefanPorojanu You want something like this? `new_list = list(set(mylist) - set(list(all_perms[0] + all_perms[1])))` Again, this will not return what you expect because of floating point precision. See [this](https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python) question. – Paolo Sep 16 '19 at 09:47