Home > Mobile >  How to add(sum) the first element to next n elements till the first element becomes zero
How to add(sum) the first element to next n elements till the first element becomes zero

Time:03-08

How to add(sum) the first element to next n elements till the first element becomes zero?

Example:

Input:

6 7 1 3 6
10

first element -> 6

a= first element =6

next element to 6 is -> 7 -> 7 3 (adding three because the element not need to exceed X)

a=6-3=3

need to add 3 to next element.

next element to 7 is 1 -> 1 3=4

a=3-3=0 (a(first element) becomes zero)

so i need to stop the loop

needed output

0 10 4 2 6 

I tried but my code not adding the remaining to next value.Is my logic is correct?.What mistake i made??

My code:

l=list(map(int,input().split()))
c=int(input())
ans=[]
for i in range(1,len(l)-1):
  a=l[0]
  l[i] =a-(l[i] a)%c 
  a-=(l[i] a)%c 
  if l[i]==c:
    i =1
  if a<=0:
    break
  
print(l)

Output i got

[6, 10, 1, 3, 6]

CodePudding user response:

Here is something that works for your example:

numbers = [6, 7, 1, 3, 6]
total = 10
i = 1
while i < len(numbers) and numbers[0] != 0:
    shift = min(total - numbers[i], numbers[0])
    numbers[i]  = shift
    numbers[0] -= shift
    i  = 1

print(numbers)

Careful, if the total you need is smaller than numbers[i] for exemple, it will reduce numbers[i] and numbers[0] will grow.

  • Related