Oct-23-2019, 05:59 PM
Yes, you are quite right to make a list of the numbers.
I found a method to try to add all combinations of additions of a list of numbers. It recursively builds a tree of all combinations.
(Oct-20-2019, 01:34 PM)Den Wrote: Anyway, after looking if the number is already in the list, and using the while method pointing j as the len(new_list) in the while method, the sum should be calculated between all the numbers of the list.The index j should get j+=-1 everytime until i and j won't encounter eachother.I disagree. If you tried "element[0] + element[1]" then you should not try "element[1] + element[0]" as it is obvious the same. That is why you should not start the inner loop with 0, but with i+1. So i and j will never meet.
I found a method to try to add all combinations of additions of a list of numbers. It recursively builds a tree of all combinations.
show_debug = True #Show debug info while running or not def find_additions(target, subtotal, input_list, debug_text): """Find combinations of a list of numbers to add to a certain number. This is a recursive function. I tries all possible combinations to add numbers from a list and counts the combinations that result in a certain target number. """ result = 0 #number of times the sum of items equals the target for i in range(len(input_list)): list_item = input_list[i] if list_item + subtotal == target: result += 1 if show_debug: print(debug_text + str(list_item)) result += find_additions(target, subtotal + list_item, input_list[i+1:], debug_text + str(list_item) + " + ") return result target = 3 input_list = [1, 2, 3] found_combinations = find_additions(target, 0, input_list, str(target) + " = ") print("number of combinations found: ", found_combinations)
Output:3 = 1 + 2
3 = 3
number of combinations found: 2
The algorithm is implemented very raw and can be greatly optimized. You might want to cut off the recursion as soon as the sum is greater than the target, but beware: can there be negative numbers in the list? Can the target be negative? Can the same number occur twice in the list?