以 X 金额购买任何 X 产品?

时间:2020-12-19 00:13:41

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

我试图解决这个问题,但我无法弄清楚。 我有 product 字典:

product = {
"shirt" : {
        "price" :300 ,
        "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}},
"pents" : {
        "price" :200 ,
        "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}
"tshirt" : {
        "price" :150 ,
        "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}
"shorts" : {
        "price" :100 ,
        "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}
            }

找到总数的最佳方法应该是什么 折扣标准,如果有人购买至少三件产品或 3 的倍数,他们会以 250 美元的价格获得三件产品?

例如,如果有人总共购买了 11 件(衬衫 = 5,裤子 = 4,T 恤 = 1,短裤 = 1)产品,那么他们的总数应该是 250 * 3 + 剩余产品 * 最低价格产品。这里剩下的项目应该是产品的最低价格(这里应该是短裤和 T 恤)。

我已经这样做了:

total_payment = 0
total_product = {"shirt" : 5,"pents":4,"tshirt":1,"shorts" 1}
total_item = sum(total_product.values())
for key, value in total_product.items():
    min_no_required_for_discount = product[key]["no_required_for_dis"].keys()
    if total_item < int(min_no_required_for_discount[0]:
       total_payment += value * product[key]["price"]
    else:
       remaining_unit  = total_item % 3
       total_pair  = (total_item - remaining_unit) // 3
       total_payment += total_pair * 250

现在我对剩余单位感到困惑。如何计算剩余单位的价格,因为剩余单位必须乘以最低价格。在上面的例子中,剩余单位将为 2,它将计算短裤和 T 恤的价格

1 个答案:

答案 0 :(得分:0)

以下是可以帮助您开始解决此问题的快速模板: [注意:使用 set() 快速获取项目差异,并使用 print() 语句确认每个步骤都是预期的] 同样,这不是一个完整的解决方案 - 但只是提供了一个很好的模板您可以快速开始。

from pprint import pprint

lowest_price_items  = ['tshirt', 'shorts']
discount_price_items = ['shirt', 'pants']
discount_Set = set(discount_price_items)

cart = ['shirt', 'shirt', 'shirt', 'shirt', 'shirt', 'pants', 'pants', 'pants', 'pants', 'tshirt', 'shorts']
cart_Set = set(cart)
low_price_goods =  cart_Set - discount_Set


pprint(product)

print(f' products: {product.keys()} ') #  first level of prod. dict.
print(product['shirt'].keys())         #  'price'  and 'no_requied_for_dis'

#       products   key1                key2
print(product['shirt']['no_reqired_for_dis']['discount_price'])  # 250
tshirt_price = product['tshirt']['price']
print(tshirt_price)

"""
total should be 250 * 3 + remaining item * lowest_price_products (tshirts, shorts) only
"""

total_items = len(cart)
print(total_items)

# modify this to calculate the final price.
if total_items > 3:
    final_price = 250 * total_items %3 + "remaining item * lowest_price_products" # select the lowest price items