【发布时间】:2017-03-29 20:04:41
【问题描述】:
我希望有人可以提供帮助。我写了以下代码:
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。所以这将永远是最低的价值。如果我尝试不同,我会遇到同样的问题(计数器总是 den(dict))。
它基本上是 2 个问题: 1. 如何确保计数器设置为所有嵌套列表的有效含义 sum<=max 的项目? 2.:我有时会收到错误消息UnboundLocalError: local variable 'result' referenced before assignment。这是什么意思,如果程序以前工作并且我没有更改代码中result 的位置,这怎么可能?
感谢您的帮助!
【问题讨论】:
-
让我们在每个帖子中保留一个问题。 minimal reproducible example | How to Ask
-
您的示例没有说明您希望 count 反映什么。
标签: python loops for-loop iteration variable-assignment