1

Let say I have A=[2,4, 3 ,1], I want to compute the sum of element inside by skipping one element in each step. What I try is:

s=[ ]
a=0
for i in range(len(A)):
    for j in range(len(A)):
        if i==j:
            continue
        else :
            a +=A[j]
    s.append(a)

When I print the result s I am getting

print(s)

s=[8, 14, 21, 30]

What I want to have is:

s=[ 8, 6, 7, 9]

Where

8=4+3+1 we skip A[0]
6=2+3+1 we skip A[1]
7=2+4+1 we skip A[2]
9=2+4+3 we skip A[3]

4 Answers 4

5

How about computing the sum and then returning the sum minus each item, using list comprehension?

sum_a = sum(A)
output = [sum_a - a for a in A]
print(output) # [8, 6, 7, 9]
Sign up to request clarification or add additional context in comments.

Comments

1

The if statement is already skipping an iteration, so all you need is to repeat the initialization. You can do this by re-initializing the sum variable (a) inside the outer loop instead of outside.

A = [2, 4, 3, 1]
s = []

for i in range(len(A)):
    a = 0
    for j in range(len(A)):
        if i == j:
            continue
        else:
            a += A[j]
    s.append(a)

print(s)

Output:

[8, 6, 7, 9]

Comments

0

I like @j1-lee answer, but here's a nifty one-liner variation on that:

output = [sum(A) - a for a in A]

Comments

0

You could build a new list from slices, excluding the unwanted value, then sum

[sum(A[:i] + A[i+1:]) for i in range(len(A))]

Or, since sum results can themselves be added, use 2 slices

[sum(A[:i]) + sum(A[i+1:]) for i in range(len(A))]

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.