python的count变量_Python中的Count变量

我希望有人能帮忙。我写了以下代码: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]]

我的程序应该迭代这些项,看看嵌套列表的值之和&lt;=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 always den(dict))。

基本上有两个问题:1。如何确保计数器设置为对所有嵌套列表有效的sum<=max的项?和2.:我有时会收到错误消息UnboundLocalError: local variable 'result' referenced before assignment。这意味着什么?如果程序在之前运行,而我不改变result在代码中的位置,这是怎么可能的呢?

谢谢你的帮助!在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值