0

我已经编写了一个逻辑来查找位置的可用数量,因为位置和数量是用字典管理的,

d={'loc2': 500.0, 'loc3': 200.0, 'loc1': 1000.0, 'loc4': 100.0, 'loc5': 50.0}

def find_combination(locations,qty): 
    new_list = sorted(locations.items(),key=lambda y: y[1],reverse=True)
    result = []
    while qty > 0:
        min_item = ''
        for item in new_list:
            if item[0] in result: 
                continue
            new_diff = abs(qty - item[1])
            if not min_item or new_diff <= min_diff:
                min_item = item[0]
                min_diff = new_diff
                min_val = item[1]
        result.append((min_item ,locations.get(min_item)))
        qty = qty - min_val
    return result

现在,当数量低于字典中的最大数量时,它会给出意想不到的结果,

print find_combination(d,500)
OUTPUT: [('loc2', 500.0)]
print find_combination(d,1000)
OUTPUT: [('loc1', 1000.0)]
print find_combination(d,750)
OUTPUT: [('loc2', 500.0), ('loc3', 200.0), ('loc5', 50.0)]
print find_combination(d,1800)
OUTPUT: [('loc1', 1000.0), ('loc1', 1000.0)] # unexpected
4

3 回答 3

2

你能解释为什么这个输出是意外的吗?将一项loc1附加到 后result, 的值qty将是800。该行将在下一次迭代中再次new_diff = abs(qty - item[1])为该项目返回最小值 (200) ,以便再次添加该项目。一旦完成,will be ,因此循环将终止。如果它们的相关数量小于变量,您是否应该只添加项目?如果是这样,您需要更多逻辑来执行此操作 - 您可以将 for 循环更改为:loc1resultqty-200whileqty

for item in [x for x in new_list if x[1] <= qty]:
于 2013-06-18T09:06:02.193 回答
1

以下代码是否符合您的要求?我使用整数除法来跟踪剩余数量。


def find_combination(locations,qty): 
    new_list = sorted(locations.items(),key=lambda y: y[1],reverse=True)
    result = []
    for item in new_list:
        quotient = int(qty / item[1])
        result.extend(quotient*[item])
        qty -= quotient*item[1]
    return result

编辑:由于您使用了 check if item[0] not in result,我假设您不想重复结果中的任何项目。在这种情况下,HennyH 的回答会很好。这个答案是行不通的。但是如果允许重复,那么这个就可以了。

于 2013-06-18T09:41:27.930 回答
1

这就是你想要的:

d={'loc2': 500.0, 'loc3': 200.0, 'loc1': 1000.0, 'loc4': 100.0, 'loc5': 50.0}
from operator import itemgetter
def find_combination(locs,qty):
    locs = sorted(d.items(),key=itemgetter(1),reverse=True) #get them in descending order
    result = []
    for loc,val in locs:
        if qty <= 0: #if we've reached the target qty then need to look no further
            break
        elif qty - val >= 0: #if we can take the val of a location and not go below zero do so
            qty -= val
            result.append((loc,val)) 
    return result 

当你

print find_combination(d,1800)
[('loc1', 1000.0), ('loc2', 500.0), ('loc3', 200.0), ('loc4', 100.0)]
>>>
于 2013-06-18T09:27:44.850 回答