我有一本字典来记录每个材料部分及其库存数量。将物料部分指定为键,将其库存量指定为值。
dictionary = {'A': 100, 'B': 200, 'C': 300,'D': 400,'E': 500,'F': 600,'G': 700,'H': 800,'I': 900,'J': 1000,'K': 1100,'L': 1200}
通过这些材料部分,我创建了由不同数量的不同材料部分组成的产品,这些材料部分以字符串 product = '1A 2B 3C'
的形式存储
每做一件产品,我都会更新材料零件的字典
for x in product.split():
value, key = x[:-1], x[-1]
dictionary[key] -= int(value)
这导致 dictionary = {'A': 99, 'B': 198, 'C': 297.....
下一部分是我被卡住的地方。当我想制作 3 个相同的产品时,我将不得不遍历字符串以更新字典 3 次。
我希望这样做,如果任何材料零件的库存不足,它会打印已经制造的产品和未完成的金额,如下所示:
dictionary = {'A': 2, 'B': 6, 'C': 9}
product = '1A 2B 3C'
quantity = 3
# Program sees that there is sufficient quantity to make 2 quantities of product with one outstanding.
#Updates the dictionary with the 2 quantities and then print:
答案 0 :(得分:1)
dictionary = {'A': 100, 'B': 200, 'C': 300,'D': 400,'E': 500,'F': 600,'G': 700,'H': 800,'I': 900,'J': 1000,'K': 1100,'L': 1200}
product = '1A 2B 3C'
quantity = 101
made = 0
while quantity:
possible = True
for x in product.split():
value, key = x[:-1], x[-1]
dictionary[key] -= int(value)
if dictionary[key]<0:possible = False
if not possible:
print("Insufficient quantity")
print(f"{made} product made at the current inventory level")
print(F"{quantity} outstanding")
for x in product.split():
value, key = x[:-1], x[-1]
dictionary[key] += int(value)
break
made +=1
quantity-=1
if quantity == 0:
print(f"{made} product successfully made")
这段代码的作用是,当系统检测到此迭代超出库存范围时,它会修复数字、停止迭代并打印消息。
我试图使代码尽可能接近您提供的逻辑。
对于测试用例 1: 数量 = 7 输出:
7 product successfully made
对于测试用例 2: 数量 = 101 输出:
Insufficient quantity
100 product made at the current inventory level
1 outstanding