 # 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] ```
``` ```
``` ```
``` ```
``` (adsbygoogle = window.adsbygoogle || []).push({}); © 2021 Python.Engineering Best Python tutorials books for beginners and professionals Become an author and write for us Architect Development For dummies Machine Learning Analysis Loops Counters NumPy NLP Regular Expressions File Handling Arrays String Variables Knowledge Database X Submit new EBook \$(document).ready(function () { \$(".modal_galery").owlCarousel({ items: 1, itemsCustom: false, itemsDesktop: [1300, 1], itemsDesktopSmall: [960, 1], itemsTablet: [768, 1], itemsTabletSmall: false, itemsMobile: [479, 1], singleItem: false, itemsScaleUp: false, pagination: false, navigation: true, rewindNav: true, autoPlay: true, stopOnHover: true, navigationText: [ "<img class='img_no_nav_mob' src='/wp-content/themes/nimani/image/prevCopy.png'>", "<img class='img_no_nav_mob' src='/wp-content/themes/nimani/image/nextCopy.png'>" ], }); \$(".tel_mask").mask("+9(999) 999-99-99"); }) ```