Selecting A Set Of Numbers From A List Which Add Up To A Given Value
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]
Solution 1:
This is one possible way to do it:
def find_combinations(list, sum):
ifnot list:
if sum == 0:
return[[]]return []
return find_combinations(list[1:], sum) + \
[[list[0]] + tail for tail in
find_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]]
Solution 2:
Here's a more generic version that checks for more than just pairs (basically, any n-tuples that add up to the required target)
deffindSum(target, L, sofar=None):
if sofar isNone:
sofar = []
ifnot target:
print(sofar)
returnif target < 0:
returnfor i,num inenumerate(L):
findSum(target-num, L[:i]+L[i+1:], sofar+[num])
Output:
In[34]: findSum(10, [1,3,11,123,5,7])
[3, 7][7, 3]
Note that it doesn't exclude similar sets
Solution 3:
The solution below should work:
wanted_num = 10
my_list = [1, 3, 11, 123, 5, 7]
for i in range(0, len(my_list)):
for j in range(0, len(my_list)):
if i + j == wanted_num:
answer = [i, j]
breakprint(answer)
This solution assumes there's only two numbers that add up to wanted_num
.
Hope it helps.
Post a Comment for "Selecting A Set Of Numbers From A List Which Add Up To A Given Value"