选择从列表中最大元素我建立从其求和到一个给定的输入值的列表中选择最大元素的程序使用输入值的Python
load_data = [1, 2, 3, 4, 10, 20]
例如用户输入30
选择20 and 10
或用户输入35
选择20, 10, 4 and 1
因为它们是可能的最大元素总结到30
或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
这并不是一件容易的事情,我不知道你了解它的复杂性(编程而言)。我想不出一种不使用递归的方法.. –
您可能会发现以下SO问题有帮助:http://stackoverflow.com/questions/3420937/algorithm-to-find-which-number-in- a-list-sum-up-to-certain-number – dodell
不简单。线性规划可能提供一个解决方案 –