我如何获得产品价格的每一种可能的组合,以达到目标成本的名单? [英] How do I get a list of every possible combination of product prices to reach a target cost?

查看:127
本文介绍了我如何获得产品价格的每一种可能的组合,以达到目标成本的名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个产品(A,BC)的列表。每个产品都有一个价格。给定一个总成本,我想找到所有可能的产品组合,等于正是成本。

像到目前为止,我已经试过的东西:

 价格的产品:
    RET = []
    对于i在范围(中间体(totalCost /价格),-1,-1):
        ret.append㈠
        对中的c的范围(1,LEN(产品)1,1):
            ret.append(INT(产品[C-1] [1] /产品[C] [1]))
 

这里是我卡住。这将让我的可能性的列表,但它仅包括后面(比当前位置)在列表属于产品。它不会环绕,包括开始,因此,给我所有的可能性。

什么我需要做的就是每一种可能性?

解决方案

 高清可能性(available_products,target_price):
    如果target_price == 0或不available_products:
        返回 []
    this_price = available_products [0]
    remaining_products = available_products [1:]
    结果= []
    对数量范围内(1 + target_price / this_price):
        remaining_price = target_price  - 数量* this_price
        如果remaining_price == 0:
            results.append([数量] + [0] * len个(remaining_products))
        其他:
            在可能性(remaining_products,remaining_price)选项:
                results.append([数量] +选项)
    返回结果
 

这是给你:

  pprint.pprint(可能性([1,2,5,10))
[[0,0,2],
 [0,5,0],
 并[1,2,1],
 [2,4,0],
 [3,1,1],
 〔4,3,0],
 [5,0,1],
 [6,2,0],
 [8,1,0],
 [10,0,0]]
 

Suppose I have a list of three products (A, B C). Each Product has a price. Given a total cost, I want to find all the possible product combinations to equal exactly that cost.

So far I've tried stuff like:

for price in product:
    ret = []
    for i in range(int(totalCost / price), -1, -1):
        ret.append(i)
        for c in range(1, len(products)+1, 1):
            ret.append(int(products[c-1][1]/products[c][1]))

And here is where I get stuck. This will get me a list of possibilities, but it will only include the products that are later (than the current location) in the list. It won't wrap around to include the beginning, and thus, give me every possibility.

What do I need to do to get every possibility?

解决方案

def possibilities(available_products, target_price):
    if target_price == 0 or not available_products:
        return []
    this_price = available_products[0]
    remaining_products = available_products[1:]
    results = []
    for qty in range(1 + target_price / this_price):
        remaining_price = target_price - qty*this_price
        if remaining_price == 0:
            results.append([qty] + [0] * len(remaining_products))
        else:
            for option in possibilities(remaining_products, remaining_price):
                results.append([qty] + option)
    return results

That gives you:

pprint.pprint(possibilities([1, 2, 5], 10))
[[0, 0, 2],
 [0, 5, 0],
 [1, 2, 1],
 [2, 4, 0],
 [3, 1, 1],
 [4, 3, 0],
 [5, 0, 1],
 [6, 2, 0],
 [8, 1, 0],
 [10, 0, 0]]

这篇关于我如何获得产品价格的每一种可能的组合,以达到目标成本的名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆