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 skipA[1]
7=2 4 1 we skipA[2]
9=2 4 3 we skipA[3]
CodePudding user response:
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]
CodePudding user response:
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]
CodePudding user response:
I like @j1-lee answer, but here's a nifty one-liner variation on that:
output = [sum(A) - a for a in A]
CodePudding user response:
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))]