简体   繁体   English

使用输入值Python从列表中选择最大元素

[英]Selecting max elements from list using input value Python

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 1 since they are the possible largest elements that sum up to 30 or 35 例如,用户输入30选择20 and 10或者用户输入35选择20, 10, 4 and 1因为它们是可能合计3035最大元素

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

This is indeed a very complex task. 这确实是一个非常复杂的任务。 This solution only provides a basic approach. 该解决方案仅提供基本方法。 It's poor and unreviewed in eg 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. 这是非常糟糕的风格。

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. ,但正如A. Grieco所说,这是解决问题的非常简单和基本的方法。

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. 如果load_data列表是常量,并且始终包含示例中的元素,那么出于优化目的,您应该只对load_data降序排序,因此,较大的元素首先处理。

Ie: 即:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM