Python | Prefix Sum Subarray to False value

Method # 1: Using the naive method
In the naive method, we simply create a new list consisting of the sum of the previous. The list value is up to 0 and restarts the procedure when a nonzero value is encountered.

# Python3 demo code
# Prefix Sum Subarray to False value
# using the naive method

  
# initializing the list of lists

test_list = [ 1 , 3 , 4 , 0 , 4 , 5 , 0 , < / code> 7 , 8 ]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# Prefix Sum Subarray to False value
# using a naive method

for i in range ( 1 , len (test_list)):

if test_list [i]: 

test_list [i] + = test_list [i - 1 ]

 
# print result

print ( "The computed modified new list:" + str (test_list))

Exit :

 The original list is: [1, 3, 4, 0, 4, 5, 0, 7, 8] The computed modified new list: [ 1, 4, 8, 0, 4, 9, 0, 7, 15] 

Method # 2: Using from_iterable () + accumulate () + groupby ()
The above three functions are combined to accomplish this specific task. In this case, the accumulation function performs the task of adding elements, the groupby function groups non-zero values, and the result is combined with the from_iterable function.

# Python3 code for demos
# Prefix Sum Subarray to False value
# from_iterable () + accumulate () + groupby ()

from itertools import groupby, accumulate, chain

 
# initializing the list of lists

test_list = [ 1 , 3 , 4 , 0 , 4 , 5 , 0 , 7 , 8 ]

  
# print the original list

print ( " The original list is: " + str (test_list))

 
# Prefix Sum Subarray to False value
# from_iterable () + accumulate () + groupby ()

res = list (chain.from_iterable (accumulate (j) 

for i, j in groupby (test_list, bool )))

 
# print result

print ( "The computed modified new list:" + str (res))

Exit:

 The original list is: [1, 3, 4, 0, 4, 5, 0, 7, 8 ] The computed modified new list: [1, 4, 8, 0, 4, 9, 0, 7, 15]