I am building a program that selects max elements from a list which sums to a given input value
load_data = [1, 2, 3, 4, 10, 20]
eg user inputs 30 select 20 and 10 or user inputs 35 select 20, 10, 4 and 1since they are the possible largest elements that sum up to 30 or 35
code
def process(m):
print m
def selection():
aux = range(len(load_data))
global value #
while aux and value > 0:
posit = max(aux) >= value
index = aux[posit]
elem = load_data[index]
value = value - posit #
del aux[posit]
process(elem)
output always prints
2
3
1
4
10
20
解決方案
This is indeed a very complex task. This solution only provides a basic approach. It's poor and unreviewed in e.g. terms of performance.
import itertools
load_data = [1, 2, 3, 4, 10, 20]
maximum = 35
def selection(data, maximum):
for count in range(1,len(data)+1):
for combination in itertools.combinations(data, count):
if maximum == sum(combination):
yield combination
i = list(selection(load_data, maximum))
print (i)
And please, avoid using global variables. This is very bad style.