希望有人能帮忙。我写了下面的代码:
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]]
我的程序应该遍历这些项,看看嵌套列表的值的总和<= 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
)和counter = 0
。所以它总是最小的值。如果我尝试不同的方法,我也会遇到同样的问题(counter always den(dict))。它基本上有两个问题:1。我怎样才能确保计数器只是设置为有效意义sum<=max
的所有嵌套列表的项目?和2。:我有时会得到错误信息UnboundLocalError: local variable 'result' referenced before assignment
。这是什么意思,如果程序以前工作过,我不改变代码中result
的位置,这是怎么可能的?谢谢你的帮助!
你的第二个问题…您应该在与返回语句相同的级别定义result
。当函数从未到达定义result
的行时,有时会得到UnboundLocalError
消息。