2016-11-15 114 views
0

我希望有人可以提供幫助。我寫了下面的代碼:Python中的計數變量

def minTransport(dict, max): 
    sum = 0 
    tempList = [] 
    counter = len(dict) 
    tempCounter = len(dict) 
    for item in get_partitions(dict): 
     for list in item: 
      for i in list: 
       sum += dict[i] 
      if sum <= limit: 
       tempList.append(list) 
       sum = 0 
      else: 
       sum = 0 
       tempList = [] 
       break 
     counter = len(tempList) 
     if counter < tempCounter: 
      result = tempList 
      tempCounter = counter 
      tempList = [] 
     else: 
      tempList = [] 
    return result 

get_partitions是一個輔助函數,返回給定字典中鍵的每一個可能的組合。例如。 dict={a:1, b:2, c:3}for item in get_partitions(dict)讓你:

[[a, b, c]] or [[a,b], [c]] or [[a], [b,c]] or [[a,c],[b]] or[[a],[b],[c]]

我的程序應該遍歷這些項目,看是否嵌套列表< =最大值,如果是這樣的話算上所有的嵌套列表中的值的總和一個物品。在上面的例子中,count可能是1 ([a,b,c]),2 (e.g. [a,b],[c]) or 3 ([a],[b],[c])。問題是我不知道如何返回最佳解決方案,這意味着嵌套列表數量最少的項目。如果我設置了counter = den(dict)tempCounter = den(dict),第一個循環後tempCounter = 0因爲程序會中斷(sum > limit)和counter = 0。所以這將永遠是最低的價值。如果我嘗試不同的方式,我有同樣的問題(counter den den(dict))。 這基本上是兩個問題:1.我怎樣才能確保計數器只是設置爲有效的所有嵌套列表sum<=max的項目? 2:我有時會收到錯誤信息UnboundLocalError: local variable 'result' referenced before assignment。這是什麼意思,如果程序工作之前可能如何,我不會在代碼中更改result的位置? 感謝您的幫助!

+2

讓我們在每篇文章中保留一個問題。 [mcve] | [問] –

+0

你的例子沒有解釋你想要反映什麼。 – TemporalWolf

回答

0

第二個問題...您應該在與return語句相同的級別定義result。當您的功能永遠不會到達您定義result的行時,您有時會收到UnboundLocalError消息。