使用输入值Python从列表中选择最大元素 [英] Selecting max elements from list using input value Python

查看:148
本文介绍了使用输入值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]

例如,用户输入30选择20 and 10或用户输入35选择20, 10, 4 and 1,因为它们是可能总计为3035

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

代码

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)

输出始终打印

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.

这篇关于使用输入值Python从列表中选择最大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆