IceDust - 1 year ago 77
Python Question

# How to find the sum of each element in a list with each other element

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.

I couldn't quite follow your code or explanation quite well, but I believe this does what you want. This is done without the `itertools` module. Using it would produce a more compact code. This is done as an alternative to `itertools`

``````lst = [1, 2, 3, 4]

def prize(L):
pair_list = []
C = 4

# Creates a list of tuples (1, 2), (1, 3), etc
for x in L:
for y in L:
# if x != y | To prevent 1 + 1 and 2 + 2 (following example)
# (y, x) not in pair_list | Prevent inverted pairs
if x != y and x + y == C and (y, x) not in pair_list:
pair_list.append((x, y))

# Return list tuples that add to constant
return pair_list

print('Possible', prize(lst))
``````

if you wish to use itertools then you would use

``````from itertools import combinations

def prize(L):
C = 4
return [(x, y) for x, y in combinations(L, 2) if x + y == C]

lst = [1, 2, 3, 4]

print('Possible', prize(lst))
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download