How can I choose some numbers from a given list so that their sum is a certain given number?
Example:
wanted_num = 10
my_list = [1, 3, 11, 123, 5, 4]=> [1, 5, 4]
How can I choose some numbers from a given list so that their sum is a certain given number?
Example:
wanted_num = 10
my_list = [1, 3, 11, 123, 5, 4]=> [1, 5, 4]
This is one possible way to do it:
def find_combinations(list, sum):if not list:if sum == 0:return [[]]return []return find_combinations(list[1:], sum) + \[[list[0]] + tail for tail infind_combinations(list[1:], sum - list[0])]
For your example, this would return:
>>> print find_combinations([1, 3, 11, 123, 5, 4], 10)
[[1, 5, 4]]