我希望有人能帮忙。我写了以下代码:
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
是一个helper函数,它返回给定dict中所有可能的键组合。例如,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]]
我的程序应该迭代这些项,看看嵌套列表的值之和<;=max,如果是这样的话,计算一个项中的所有嵌套列表。在上面的例子中,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
)和{sum<=max
的项?和2.:我有时会收到错误消息UnboundLocalError: local variable 'result' referenced before assignment
。这意味着什么?如果程序在之前运行,而我不改变result
在代码中的位置,这是怎么可能的呢?
谢谢你的帮助!在
你的第二个问题。。。{你应该在同一级别定义你的语句。有时,当函数从未到达定义
result
的行时,会得到UnboundLocalError
消息。在相关问题 更多 >
编程相关推荐