Search code examples
pythonpython-3.xlistfor-loopwhile-loop

Sum the elements in an array until its divisible by 5 and continue the same in python


Please help me get the logic in python Input is sample= [1,2,3,4,5,6,7,8,9,10] Excepted output is Result=[15,40] Explanation checks each element in sample and adds one by one until the value is divisible by 5 (so 1+2+3+4+5=15) And the check and add continues (so 6+7+8+9+10=40) thus the result is in list result =[15,40]

I tried For i in sample If(sample[i] % 5==0): But it is not continuing after the conditions


Solution

  • This will help:

    sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    result = []
    current_sum = 0
    
    for num in sample:
        current_sum += num
        if num % 5 == 0:
            result.append(current_sum)
            current_sum = 0
    
    if current_sum != 0:
        result.append(current_sum)
    
    print(result)