Python Forum

Full Version: Sum of list items
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone

If the sum of the numbers in the list1 is not 4000, it should give the closest value to 4000. The maximum number of elements of the output is 6.

For example

Sum = 4000

list1 = [400, 600, 600, 1000]

output1 = [400,600, 1000,1000,1000]
output2 = [600, 600, 600, 600, 600,1000]
...

outputn = [1000,1000, 1000,1000]

If the sum was 4005, the results would still be the same.

what code do i need?

Thank you in advance for your help.
Quote:what code do i need?
What have you tried?
I have this one but It doesn't work as I wanted.

import itertools
import functools

test_matrix = []
stuff = [100,500,300,200]
for L in range(0, len(stuff)+1):
    
   for subset in itertools.combinations(stuff, L):
         test_matrix.append(subset)
       
while True:       
    res = functools.reduce(lambda i, j: i if 4000 < sum(j)
                          else j, test_matrix)
    
    
    test_matrix.remove(res)
    a = sum(int(b) for b in res)

    print (a)
    print ("Maximum sum sublist is : " + str(res))