0

I'm trying to sum each pair of values in this a list. Here's a short example, but I'd like my function to work with any length list.

So, for x = [1,2,3] I'd like to return the value of 12. I want to condense this:

y = 0
for i in x:
    y += x[0] + x[1] 
    y += x[1] + x[2]
    y += x[0] + x[2]
return y

I'm not sure if my question is clear, and I'll clarify if there are any questions.

3 Answers 3

2
for i in range(0, len(x)-1): 
        for j in range(i+1, len(x)):
            sum+=x[i]+x[j]

Hopefully I wrote this right, it's a been a bit since I touched Python. But essentially, you have marker one and marker two - marker one starts at 0 and counts up every time the outer loop increments, and j starts at i+1 and counts up to the end of the array. Then you sum i and j, and by doing so, you eventually sum all combinations together. It's len(x)-1 because i stops at the second to last result (and indexes start at 0, so len(x) is 1 more than the value of the last index, but range doesn't include the end value), and j stops at the last index (len(x)-1).

Sign up to request clarification or add additional context in comments.

Comments

0

Try combinations:

from itertools import combinations

x = [1,2,3]
y = 0
for p in combinations(x, 2):
    y += sum(p)

Combinations

Comments

0
import itertools
y = sum( sum(combo) for combo in itertools.combinations( x, 2 ) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.