How do I get a list of every possible combination of product prices to reach a target cost?

后端 未结 2 1045

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 co

2条回答
  •  没有蜡笔的小新
    2021-01-15 02:01

    The itertools module offers combinatoric generators to help with problems such as this:

    >>> from itertools import *
    >>> prices = dict(a=10, b=15, c=8, d=2, e=5)
    >>> total_cost = 20
    >>> for r in range(1, 30):
            for t in combinations_with_replacement(prices, r):
                    cost = sum(prices[p] for p in t)
                    if cost == total_cost:
                            print t
    

提交回复
热议问题