假设我有一个三种产品的清单(A,B,C)。每种产品都有价格给定一个总成本,我想找到所有可能的产品组合完全等于该成本。
到目前为止,我试过这样的事情:

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

这就是我陷入困境的地方这将为我提供一个可能性列表,但它将只包括列表中晚于(当前位置)的产品它不会包含开头,因此,给我一切可能。
我需要做什么才能得到所有的可能性?

最佳答案

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

这给了你:
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]]

10-06 04:37
查看更多