Iterate through sum combinations in Python 3

后端 未结 3 1496
野趣味
野趣味 2021-01-28 03:44

I\'m look for a way to find all combinations of sums with elements of a Fibonacci sequence with a given limit which equal that same value. I know that combinations()

3条回答
  •  萌比男神i
    2021-01-28 04:39

    To find all the combinations with the desired sum, append each combination to a result list:

    def combinations_with_sum(sequence, desired_sum):
        results = []
        for i in range(len(sequence)):
            results.extend([combination for combination in combinations(sequence, i)
                            if sum(combination) == desired_sum])
        return results
    

提交回复
热议问题