Find all combinations of a list of numbers with a given sum

前端 未结 5 733
时光取名叫无心
时光取名叫无心 2020-11-29 02:57

I have a list of numbers, e.g.

numbers = [1, 2, 3, 7, 7, 9, 10]

As you can see, numbers may appear more than once in this list.

I n

5条回答
  •  情书的邮戳
    2020-11-29 03:46

    @qasimalbaqali

    This may not be exactly what the post is looking for, but if you wanted to:

    Find all combinations of a range of numbers [lst], where each lst contains N number of elements, and that sum up to K: use this:

    # Python3 program to find all pairs in a list of integers with given sum  
    from itertools import combinations 
    
    def findPairs(lst, K, N): 
        return [pair for pair in combinations(lst, N) if sum(pair) == K] 
    
    #monthly cost range; unique numbers
    lst = list(range(10, 30))
    #sum of annual revenue per machine/customer
    K = 200
    #number of months (12 - 9 = num months free)
    N = 9
    
    print('Possible monthly subscription costs that still equate to $200 per year:')
    #print(findPairs(lst, K, N)) 
    findPairs(lst,K,N)
    

    Results:

    Possible monthly subscription costs that still equate to $200 per year:
    Out[27]:
    [(10, 11, 20, 24, 25, 26, 27, 28, 29),
     (10, 11, 21, 23, 25, 26, 27, 28, 29),
     (10, 11, 22, 23, 24, 26, 27, 28, 29),
    

    The idea/question behind this was "how much can we charge per month if we give x number of months free and still meet revenue targets".

提交回复
热议问题