首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定义搁置(inventory,product_list):它与字典有关

定义搁置(inventory,product_list):它与字典有关
EN

Stack Overflow用户
提问于 2016-11-15 11:19:53
回答 3查看 437关注 0票数 0

问题是:

这是家庭作业的最后一个问题,它给我带来了最大的麻烦。我花了这么多时间在上面,但是我还是不能得到正确的结果。我不确定错误是什么,我假设这是一个逻辑错误。为了避免混淆,我将完整地复制作业,而不是尝试总结。一个详细的回应解释解决方案是如何达成的也是有帮助的,因为我想更好地理解这个概念。

我们希望通过跟踪当前每种产品的数量来跟踪我们商店的库存。我们将使用一个名称为:amount键-值对的字典。名称是一个字符串,金额是一个整数。

我们将定义搁置函数,该函数接受一个字典作为库存和一个(名称,编号)对列表,每个对都指示我们应该通过添加编号来更新该命名产品的库存。(这个数字可以是负数)。第二个参数被命名为product_list。第一次提到产品时,需要将其添加到库存字典中。当它的计数达到零时,它应该保留在具有零计数的库存中。但是计数永远不能变成负数。如果某个特定项目的库存为负值,则必须引发ValueError以指示某些产品的数量低于零。-返回值: None。(对库存进行适当的更改)。-建议:使用try-except块添加项目。(不过,您可能会找到其他解决方案,这没问题)。- Requirement:当商品数量为负时抛出ValueErrors,构造异常时使用“产品金额为负”字符串。

示例:

代码语言:javascript
复制
d = {"apple":50, "pear":30, "orange":25}

ps = [("apple",20),("pear",-10),("grape",18)] 

shelve(d,ps)
d 
{'pear': 20, 'grape': 18, 'orange': 25, 'apple': 70}

shelve(d,[("apple",-1000)])
Traceback (most recent call last):

ValueError: negative amount for apple

我的代码:

代码语言:javascript
复制
def shelve(inventory,product_list):
    invt = {}
    count = 0
    try:
        for x in product_list:
            if x== True:
                invt{x} = product_list.shelve{x}
                count += key

    except ValueError:
    print ('negative amount for (product)')

其他示例:

检查d = {"apple":50} shelve(d,[("apple",20),("apple",-30)])是否将d修改为{"apple":40}

检查shelve({}, [("apple",-20)])是否引发了ValueError

谢谢你的帮助。

EN

回答 3

Stack Overflow用户

发布于 2016-11-15 11:51:05

给出了注释的答案,并假设如果任何库存项目低于0,则需要避免副作用

代码语言:javascript
复制
def shelve(inventory, product_list):
    adj = dict(inventory)
    for product, amount in product_list:
        adj[product] = adj.get(product, 0) + amount

    if any(v < 0 for v in adj.values()):
        raise ValueError("Negative amount for product")

    inventory.update(adj)

>>> d = {"apple":50, "pear":30, "orange":25}
>>> shelve(d, [("apple",20),("pear",-10),("grape",18)])
>>> d
{'apple': 70, 'grape': 18, 'orange': 25, 'pear': 20}
>>> shelve(d,[("apple",-1000)])
ValueError                                Traceback (most recent call last)
...
ValueError: Negative amount for product
票数 1
EN

Stack Overflow用户

发布于 2016-11-15 11:48:25

假设如果字典中的一些值在添加了一些数字后变为负数,那么您将引发ValueError异常并反转操作。

代码语言:javascript
复制
def shelve(inventory, product_list):
    # Here you iterate through the product_list.
    for p in product_list:      
        # The product_list contains pairs (tuples), e.g. ('apple', 20) and you
        # check if the first element of the pair, i.e. p[0] exists as a key 
        # in the dictionary.
        if p[0] in inventory:   
            # You use try-except to raise and then handle the exception 
            try:
                # If key p[0] exists in the dictionary then you add the value from the pair, i.e. p[1] to existing key's value in the dictionary  
                inventory[p[0]] += p[1]
                # If the value of the key p[0] is negative you raise an exception with the message in the parentheses 
                if inventory[p[0]] < 0:
                    raise ValueError('negative amount for product')
            # Here you handle the exception. You print the message and subtract the value you added. 
            except ValueError as ve:
                print(ve)
                inventory[p[0]] -= p[1]
        # If the key p[0] does not exist in the dictionary, then you add it to the dictionary and assign value p[1] to it.  
        else:
            inventory[p[0]] = p[1]
    #Here you just print the contents of inventory
    print(inventory)        

# These are just examples to test the code.
d = {"apple":50, "pear":30, "orange":25}
ps = [("apple",20),("pear",-10),("grape",18)] 

shelve(d, ps)
shelve(d,[("apple",-1000)])

这只是你如何解决你的任务的一个例子。还有其他(可能更好)的变种。

票数 0
EN

Stack Overflow用户

发布于 2016-11-15 12:01:50

以下代码将执行必要的检查(阅读注释):

代码语言:javascript
复制
d = {"apple":50, "pear":30, "orange":25}
ps = [("apple",20),("pear",-10),("grape",18)]


def shelve(sh: dict, items: list) -> dict:
    for name, value in items:  # iterate over list and split tuples
        if name not in sh:  # add item key if it doesn't already exist
            sh[name] = 0

        if sh[name] + value < 0:  # raise ValueError if sum will be negative
            raise ValueError('negative amount for (%s)' % name)

        sh[name] += value  # apply change to dictionary

    return sh  # not necessary but can be good for testing

这段代码应该相当快,因为它不会花费时间遍历整个字典。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40601452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档