Python | Increment 1 in a list based on a template

Examples :

`  Input:  [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1 , 1]  Output:  [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]  Input:  [1, 0 , 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1]  Output:  [1, 0, 2, 0, 0 , 0, 3, 3, 0, 0, 4, 4, 4, 0, 5, 0, 6] `

Approach # 1: Naive Approach

This is a naive approach to this problem. It uses two variables “previous” and “grp” to store the previously increased number and to store the number 1 in the group. Now, using a for loop, increment 1 accordingly.

 ` # Python3 program to increment 1 in ` ` # list based on template ` ` `  ` def transform (lst): ````     previous = 0 grp = 0 for elem in lst: if < / code> elem and not previous: grp + = 1 previous = elem yield (grp if elem else 0 )   # Driver code lst = [ 0 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 1 , 1 , 1 ] x = (transform (lst)) res = [] for i in range ( 0 , len (lst)): res.append ( next (x)) print (res) ```

Exit:

` [0, 1, 0, 0, 2, 2 , 0, 0, 0, 3, 3, 3] `

Approach # 2 Using counter , chaining and group login from the itertools module.
This is an efficient and more pythonic approach to this problem, in which we use count , chain and groupby from the itertools module .

 ` # Python3 program to increase by 1 in ` ` # list on template based ` ` from ` ` itertools ` ` import ` ` * `    ` def ` ` transform (lst): `   ` c ` ` = ` ` count (` ` 1 ` `) ` ` return ` ` list ` ` (chain (` ` * ` ` [` ` list ` ` (g) ` ` if ` ` k! ` ` = ` ` 1 ` ` else ` ` [` ` next ` ` (c)] ` ` * ` ` len ` ` (` ` list ` ` (g)) ` ` for ` ` k, g ` ` in ` ` groupby (lst)])) `   ` # Driver code ` ` lst ` ` = ` ` [` 0 `, ` ` 1 ` `, 0 , 0 , 1 , 1 , 0 , 0 , 0 , 1 , 1 , 1 ] ```` print (transform (lst)) ```

Exit:

` [0, 1, 0, 0 , 2, 2, 0, 0, 0, 3, 3, 3] `