I am programming a knapsack encryption algorithm. I am new to Python programming. I have a list and an integer value I have determined. I want to find what elements in my list will sum up to my integer value. I can get it running for two elements or less but I can not run it for more than two elements.
Assume:
privkey = [2,3,6,13,27,52]
cipher = 9
My current function can run the scenario above:
searchList = []
for i, number in enumerate(privkey[:-1]):
complementary = cipher - number
if complementary in privkey[i+1:]:
searchList.append(number)
searchList.append(complementary)
print("Solution Found: {} and {}".format(number, complementary))
break
else:
print("No solutions exist")
print(searchList)
The expected output of this will be [3,6] and indeed works.
However if cipher is changed to a condition which requires the sum of more than three characters for example:
cipher = 11
This would require the sum of privkey[0]+privkey[1]+privkey[2].
How can I create a code that covers these bases as well?