Abdul Basit Niazi
Abdul Basit Niazi

Reputation: 7

sum of elements but skip one element in each iteration in python

skip one element of array in each iteration while doing a sum of array in python , for example if I have a array [0,2,3,5,6,5,8,9] how can I do sum for first 7 element then on next iteration sum of the rest array except first element

for x in range(len(arr)):
   maxi = max(sum(arr), maximum)

   return maxi

this return the sum of the whole array but I want to skip one element in each iteration and then skip the other element but add the previous element that was skipped

Upvotes: 1

Views: 3813

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

Sum the array once then subtract one element at a time:

li = [0, 2, 3, 5, 6, 5, 8, 9]
array_sum = sum(li)

for n in li:
    print('sum of array is', array_sum, ', without', n, 'the sum is', array_sum - n)

outputs

sum of array is 38 , without 0 the sum is 38
sum of array is 38 , without 2 the sum is 36
sum of array is 38 , without 3 the sum is 35
sum of array is 38 , without 5 the sum is 33
sum of array is 38 , without 6 the sum is 32
sum of array is 38 , without 5 the sum is 33
sum of array is 38 , without 8 the sum is 30
sum of array is 38 , without 9 the sum is 29

If you are only interested in the max sum:

li = [0, 2, 3, 5, 6, 5, 8, 9]
print(max(sum(li) - n for n in li))

At this point, you don't even need the loop. By definition, we'll get the max sum when substructing the smallest element.

print(sum(li) - min(li))

Upvotes: 3

Related Questions