2017-06-04 216 views
-3

比方說,我有一堆的命令,我需要填寫Python訂單填充循環?

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5] 

的我的起始量說100

startingvolume = 100 

我想通過訂單迭代,直到我的音量/順序填充

所以第一個訂單將是我的初始100減去39.789032的第一個訂單,其中60.2110968的訂單仍然需要填寫。什麼是填充我的訂單,直到我的起始量爲0,最Python化的方式?

+3

等都不是免費的編碼服務。你必須嘗試自己解決問題。如果無法正常工作,請發佈您嘗試的內容,我們會幫助您解決問題。 – Barmar

+1

這是功課嗎? – jordanm

+2

這看起來像揹包問題https://en.wikipedia.org/wiki/Knapsack_problem。這是一個非常困難的問題,許多偉大的思想家都在努力解決問題。 – setholopolus

回答

0

NumPy使這個很簡單。

import numpy as np 

def fill(orders, startingvolume): 
    orders = np.asarray(orders) 
    return orders[orders.cumsum() <= startingvolume] 

鑑於你例如輸入,將返回:

array([ 39.789032 , 36.023618 , 3.0539913, 20.  ]) 

哪一個是你已經完全填補了訂單。要獲得剩餘的一個,你部分填充:

orders[orders.cumsum() >= startingvolume][0] 
+0

在我的解決方案中,我發現最好的填充順序是'(39.789032,36.023618,3.0539913,20.0,1.0)',它可以填充99.86664和100。您的最佳訂單缺少一個「1.0」的元素。 –

-1

使用for循環。 如果你不知道這是什麼,你應該下載一個應用程序,或搜索YouTube的基本python。我推薦新波士頓的編程教程。

0

很多方面,這裏有一個:

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5] 
startingvolume = 100 

for i in range(len(orders)): 
    qty = startingvolume if startingvolume < orders[i] else orders[i] 
    orders[i] -= qty 
    startingvolume -= qty 
    if not startingqty: 
     break 

這將扣除儘可能地從每一個訂單,直到什麼都不剩,然後停止。

0

可以使用combinationsitertools模塊和max(),像這樣的例子解決你的問題:

from itertools import combinations 

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5] 
startingvolume = 100 

sub = [] 
for k in range(1, len(orders)): 
    sub.append(max([[j, sum(j)] for j in combinations(orders, k) if sum(j) <= startingvolume], key = lambda x: x[1])) 

best_order, fill_max = max(sub, key = lambda x: x[1]) 
print("best order is: {}\nMax to fill from starting volume is: {}" 
            .format(best_order, fill_max)) 

輸出:

best order is: (39.789032, 36.023618, 3.0539913, 20.0, 1.0) 
Max to fill from starting volume is: 99.86664