Home > Software engineering >  Editing the sum of array elements to equal a value in Python
Editing the sum of array elements to equal a value in Python

Time:09-27

I have a list. I want the sum of the elements to be equal to n. Because of this reason, the last element of my list is changeable. For example:

L=[1,2,3,4]
n=5
        
for first element = 1 < 5     resume
    for second element = (1 2) < 5 resume
        for third element = (1 2 3) > 5 break / for equal 
        
Lnew[1,2,2]

or

L=[3,4,5]
n=6

for first element = 3 < 5     resume
    for second element = (3 4) > 5 break / for equal 
        
Lnew[3,3]

CodePudding user response:

Iterate over each value in the list, append if sum so far is smaller than n. If not, append the difference and break:

L = [3,4,5]
n = 6

s = 0 # sum so far, increases in the for-loop
Lnew = [] # empty list, values are appended in for-loop

for i in L:
    if i   s <= n: 
        # if the value plus the sum so far is smaller than n: append to list and increase s
        Lnew.append(i)
        s  = i
    else:
        # else, append difference and stop the for-loop
        Lnew.append(n - s)
        break

CodePudding user response:

That's pseudo-code, not python, and I don't really understand what you wrote to be honest

a solution in python is

my_array = [......]
N = 999

my_array[-1] = N-sum(my_array[:-1])

changes the last element to N minus the sum of every element except the last

  • Related