0
def find_the_best_solution(shipping_request, list, current_solution, best_shipping_solution):
    if shipping_request == {}:
        return current_solution

    for item in shipping_request:
        for i in range(0,len(list), 1):
            length_of_combination = i+1
            combinations = itertools.combinations(list, length_of_combination)
            for x in combinations:
                if sum(x) >= shipping_request[item]:
                    if sum(x) > shipping_request[item]:
                        current_solution['wastage'] += (sum(x) - shipping_request[item])
                    current_solution['number_of_containers'] += length_of_combination
                    current_solution['distribution'][item] = x
                    temp_request = shipping_request
                    del temp_request[item]
                    temp_list = list
                    for y in x:
                        temp_list.remove(y)
                    solution = find_the_best_solution(temp_request, temp_list, current_solution, best_shipping_solution)
                    if solution['wastage'] < best_shipping_solution['wastage']:
                        best_shipping_solution = solution
                    elif solution['wastage'] == best_shipping_solution['wastage']:
                        if solution['number_of_containers'] < best_shipping_solution['number_of_containers']:
                            best_shipping_solution = solution

    return best_shipping_solution   

这给出了以下错误-“运行时错误:迭代期间字典大小更改”

我究竟做错了什么?我该怎么做?

4

1 回答 1

1

这与 无关itertools.combinations,您正在尝试更改正在迭代的数据结构,这是不允许的:

Runtime error: dictionary size changed during iteration

您正在尝试在迭代字典时从字典中添加或删除键。一种解决方法是迭代for key in list(dictionary)生成字典键的副本列表,因此您仍然可以修改底层字典,但是您可能还想重新考虑您的一般方法。

导致错误的行是:

for item in shipping_request:

    for i in range(0,len(list), 1):
            ...
            for x in combinations:
                if sum(x) >= shipping_request[item]:
                    if sum(x) > shipping_request[item]:
                        ...
                    temp_request = shipping_request
                    del temp_request[item] # you are trying to delete a key from 
                                           # shipping_request as you iterate it

也许你想制作一个浅拷贝,例如。temp_request = dict(shipping_request)它创建了一个引用相同对象的新字典。但是,您可能希望 aimport copy; copy.deepcopy递归地复制字典中的每个对象。

于 2013-05-24T08:02:36.547 回答