【问题标题】:Defining shelve(inventory,product_list): it pertains to dictionaries定义 shelve(inventory,product_list):它与字典有关
【发布时间】:2017-03-28 20:10:13
【问题描述】:

问题:

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

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

我们将定义 shelve 函数,它接受一个字典作为库存 以及一个 (name, number) 对的列表,每个对都表明我们应该通过添加数字来更新该命名产品的库存。 (数字可能是 消极的)。第二个参数名为 product_list。 首次提及产品时,需要将其添加到 库存字典。当它的计数达到零时,它应该保持在 零计数的库存。但计数绝不能变为负数。 如果任何特定项目的库存变成负数,您必须提高 一个 ValueError 表示某些产品的数量低于零。 - 返回值:无。 (对现有的库存进行更改)。 - 建议:使用 try-except 块添加项目。 (不过,您可能会找到其他解决方案,这没关系)。 - 要求:只要项目的计数变为负数,就会引发 ValueErrors;采用 构造异常时的字符串“产品的负金额”。

例子:

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

我的代码:

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

感谢您的帮助。

【问题讨论】:

  • 如果您执行 shelve({}, [('apple', -20), ('apple, 30)]) 会引发 ValueError 还是 {'apple' : 10}
  • 你有except except ValueError - 应该只是except ValueError吗?
  • @StevenSummers 我相信它应该返回 {'apple' : 10}
  • @RobGwynn-Jones 它应该只是除了 ValueError,我编辑了错误。我的道歉

标签: python python-3.x dictionary python-3.5


【解决方案1】:

给出 cmets 的答案并假设您需要避免任何库存物品低于 0 时的副作用:

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

【讨论】:

    【解决方案2】:

    以下代码将执行必要的检查(读取 cmets):

    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
    

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

    【讨论】:

      【解决方案3】:

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

      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)])
      

      这只是您如何解决作业的一个示例。还有其他(可能更好)变体。

      【讨论】:

      • 你能解释一下你做了什么吗?我对你的所作所为并不肯定。
      • @Soccerninja 我添加了 cmets。希望这会有所帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多