Python中的计数变量
我希望有人可以提供帮助。我写了下面的代码: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
的位置? 感谢您的帮助!
第二个问题...您应该在与return语句相同的级别定义result
。当您的功能永远不会到达您定义result
的行时,您有时会收到UnboundLocalError
消息。
让我们在每篇文章中保留一个问题。 [mcve] | [问] –
你的例子没有解释你想要反映什么。 – TemporalWolf