Selecting max elements from list using input value

2019-05-31 10:09发布

问题:

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  # <- value is the input 
    while aux and value > 0:
        posit = max(aux) >= value 
        index = aux[posit]
        elem = load_data[index]
        value = value - posit # <- subtract max value from input and repeat process 
        del aux[posit]  
        process(elem)

output always prints

2
3
1
4
10
20

回答1:

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.



回答2:

Here you are:

load_data = [1, 2, 3, 4, 10, 20]
global value 
value = 30

def process(m): 
    print m

def selection():
    # make a local copy of load_data
    data = load_data[:]
    global value  # <- value is the input 
    while data and (value > 0):
        maxval = max(data)
        posix = data.index(maxval)
        if posix >=0:
            value = value - data[posix] # <- subtract max value from input and repeat process 
            process(data[posix])
            data.pop(posix)  
selection()

, but as A. Grieco said, it's very simple and basic aproach to problem.

If load_data list is constant, and always has elements from example, then you should just sort descending the load_data first, so the bigger elements are processing first, for optimization purposes.

I.e:

load_data = [1, 2, 3, 4, 10, 20]
global value 
value = 30

def process(m): 
    print m

def selection():
    # make a local copy of load_data
    data = sorted(load_data[:],reverse=True)
    global value  # <- value is the input 
    for v in data:
        if value -v >= 0:        
            value -= v 
            process(v)
        if value -v == 0:
            break

selection()


标签: python max