从字典中查找可用数量

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


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


梦里花落0921
浏览 197回答 3
3回答

qq_笑_17

您能解释一下为什么该输出是意外的吗?将一项loc1附加到后result,值qty将为800。该行将在下一次迭代时再次new_diff = abs(qty - item[1])为该项目返回一个最小值(200)loc1,因此该项目将result再次添加到该项目。完成后,qty将是-200,因此while循环将终止。如果它们的关联数量小于变量,是否应该仅添加项目qty?如果是这样,则需要更多逻辑来执行此操作-您可以将for循环更改为:for&nbsp;item&nbsp;in&nbsp;[x&nbsp;for&nbsp;x&nbsp;in&nbsp;new_list&nbsp;if&nbsp;x[1]&nbsp;<=&nbsp;qty]:

慕娘9325324

这就是您想要的:d={'loc2': 500.0, 'loc3': 200.0, 'loc1': 1000.0, 'loc4': 100.0, 'loc5': 50.0}from operator import itemgetterdef find_combination(locs,qty):&nbsp; &nbsp; locs = sorted(d.items(),key=itemgetter(1),reverse=True) #get them in descending order&nbsp; &nbsp; result = []&nbsp; &nbsp; for loc,val in locs:&nbsp; &nbsp; &nbsp; &nbsp; if qty <= 0: #if we've reached the target qty then need to look no further&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; elif qty - val >= 0: #if we can take the val of a location and not go below zero do so&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; qty -= val&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.append((loc,val))&nbsp;&nbsp; &nbsp; return result&nbsp;你什么时候print find_combination(d,1800)[('loc1', 1000.0), ('loc2', 500.0), ('loc3', 200.0), ('loc4', 100.0)]>>>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python