【问题标题】:Count variable in PythonPython中的计数变量
【发布时间】: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 &gt; limit)和counter = 0。所以这将永远是最低的价值。如果我尝试不同,我会遇到同样的问题(计数器总是 den(dict))。 它基本上是 2 个问题: 1. 如何确保计数器设置为所有嵌套列表的有效含义 sum&lt;=max 的项目? 2.:我有时会收到错误消息UnboundLocalError: local variable 'result' referenced before assignment。这是什么意思,如果程序以前工作并且我没有更改代码中result 的位置,这怎么可能? 感谢您的帮助!

【问题讨论】:

标签: python loops for-loop iteration variable-assignment


【解决方案1】:

您的第二个问题...您应该将result 定义在与您的退货声明相同的级别。当您的函数从未到达您定义result 的行时,您有时会收到UnboundLocalError 消息。

【讨论】:

    猜你喜欢
    • 2016-03-12
    • 2020-08-23
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多