Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3042
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 07:21

    Another python solution would be to use the itertools.combinations module as follows:

    #!/usr/local/bin/python
    
    from itertools import combinations
    
    def find_sum_in_list(numbers, target):
        results = []
        for x in range(len(numbers)):
            results.extend(
                [   
                    combo for combo in combinations(numbers ,x)  
                        if sum(combo) == target
                ]   
            )   
    
        print results
    
    if __name__ == "__main__":
        find_sum_in_list([3,9,8,4,5,7,10], 15)
    

    Output: [(8, 7), (5, 10), (3, 8, 4), (3, 5, 7)]

提交回复
热议问题