Sum of list items - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Sum of list items (/thread-32382.html) |
Sum of list items - tristanfermat - Feb-06-2021 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. RE: Sum of list items - Larz60+ - Feb-06-2021 Quote:what code do i need?What have you tried? RE: Sum of list items - tristanfermat - Feb-06-2021 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)) |