'Algorithm to find a list of numbers that sum up to a certain number
I'm learning python and I have a problem with this task
I have a list of numbers 0<=n<=(end), and I want to find all combinations of lists with 6 elements whose elements sum up to a certain number S
I'll use the list created by the function to check some conditions which I think would be another kind of task. Right now, I'm looking for an effective way to do the task above! I tried to use Brute-force, but I guess the time complexity gets exponential!
Pseudocode or suggestion of a known algorithm would also be nice for me! I just a piece of advice, thank you.
For example,
def f(end, S):
#definition of the function
input f(14, 14)
output [14, 0, 0, 0, 0, 0] [0, 14, 0, 0, 0, 0] ...(and so on)... [0, 0, 3, 0, 7, 4] [0, 0, 3, 0, 6, 5] (and so on)...
Below is information about the condition I mentioned above, still my main question is about the task above! So you can just ignore the below part
I have three different functions that return a String(the only possible outputs are A, B, C or (none). eg) f1(list) --> 'A' f2(list) --> 'B' f3(list) --> 'C'
I will put the list created by the function I asked for into those functions and find out which cases of lists lead the three functions to return a String different from each other, while they all do not return (none)(f1, f2, f3 should return A or B or C). I will make a loop for each list and find out which of them meets this condition.
Solution 1:[1]
You can do -
def f(Num, List):
n = Num
l = List
for i in range(len(List)):
if len(List) > 0 and len(List) != 1:
x= List.pop(0)
y= List.pop(0)
if x + y == Num:
print(str(x) + " and " + str(y) + " are a sum of " + str(Num))
else:
# print("the list has no more values")
exit(0)
f(10, [5, 5, 8, 2, 3, 4, 3]) # 3, 4, 3 will not be checked
the reason why 3,4,3 will not be checked is because the program does not support the sums of more then 2 numbers, imagine if you give this list [4, 4, 2] and want to find 10 as its sum, the program will not do anything and just quit, because it does not support 3 or more numbers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Akshaj Trivedi |
