Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

Example:

Input:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading