Python中的Count变量

2024-04-26 22:36:23 发布

您现在位置: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是一个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)和{}。所以这永远是最低值。如果我尝试不同的方法,我会遇到同样的问题(counter always den(dict))。 基本上有两个问题:1。如何确保计数器设置为对所有嵌套列表有效的sum<=max的项?和2.:我有时会收到错误消息UnboundLocalError: local variable 'result' referenced before assignment。这意味着什么?如果程序在之前运行,而我不改变result在代码中的位置,这是怎么可能的呢? 谢谢你的帮助!在


Tags: orin列表forgetlencounterresult