I need to write a function where, for any list, each element in the list is added together and to see if it equals a constant.
For example:
L = [1, 2, 3, 4]
The sum of each element added together is 1+2=3
, 1+3=4
, 1+4=5
, 2+3=5
, 2+4=6
, 3+4=7
.
And then to test each of these results to a constant eg if the output = C where C = 3
, and append the two numbers that were summed to equal the constant to a new list to be printed.
I am not allowed to use indexing here.
So far I am able to add the numbers in pairs along the list:
def prize(L):
possible = []
C = 4
prevprev = L.pop(0)
prev = L.pop(0)
print("initial", prevprev, prev)
for n in L:
i = prev + prevprev
prevprev = prev
prev = L.pop(0)
if i == C:
possible.append(i)
return possible
print("possible ", possible)
But for some reason this misses out the last 2 elements in the list when iterating over it.